簡體   English   中英

pandas dataframe:seaborn Z32FA6E1B78A9D4028953E605Z4A2作為索引的多列日期時間欄

[英]pandas dataframe : seaborn plot bar with multiple columns and datetime as index

我有 dataframe 有兩列這樣的(以日期為索引):

在此處輸入圖像描述

我的目標是 plot 條與 seaborn 像這樣(使用 excel):

在此處輸入圖像描述

我關注了這里的討論:在此處輸入鏈接描述

我知道我必須使用融化。 但是當我輸入以下代碼時,結果是索引(日期)消失(由數字替換)並且 dataframe 結構更改如下:

# pd.melt(df, id_vars=['A'], value_vars=['B'])
premier_melt = pd.melt(final_mada_df,id_vars=["Confirmed"],value_vars = ["Recovered"])

在此處輸入圖像描述

我們如何才能正確解決 plot 條與 seaborn 的此類問題

提前致謝


我按照以下建議將代碼放在下面:

# main dataframe 
  df2
       Recovered Confirmed
3/20/20   0          3
3/21/20   0          0
3/22/20   0          0
3/23/20   0          9

df2.stack()

出去:

3/20/20  Recovered    0
         Confirmed    3
3/21/20  Recovered    0
         Confirmed    0
3/22/20  Recovered    0
                     ..
5/4/20   Confirmed    0
5/5/20   Recovered    2
         Confirmed    2
5/6/20   Recovered    0
         Confirmed    7
Length: 96, dtype: int64

df2.rename(columns={'level_1':'Status',0:'Values'})

出去:

       Recovered Confirmed
3/20/20   0         3
3/21/20   0         0
3/22/20   0         0
3/23/20   0         9
3/24/20   0         5

但是當我輸入以下代碼時,出現錯誤:

# plot 
ax = sns.barplot(x=df2.index,y='Values',data=df2,hue='Status')

ValueError: Could not interpret input 'Values'
  • 使用.stack().melt將 dataframe 從寬格式轉換為長格式,如下所示。

導入和示例數據

import pandas as pd
import seaborn as sns
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt

# optional graph format parameters
plt.rcParams['figure.figsize'] = (16.0, 10.0)
plt.style.use('ggplot')

# data
np.random.seed(365)
data = {'Confirmed': [np.random.randint(10) for _ in range(25)],
        'date': pd.bdate_range(datetime.today(), freq='d', periods=25).tolist()}

# dataframe
df = pd.DataFrame(data)

# add recovered
df['Recovered'] = df['Confirmed'].div(2)

| date                |   Confirmed |   Recovered |
|:--------------------|------------:|------------:|
| 2020-05-12 00:00:00 |           4 |         2   |
| 2020-05-13 00:00:00 |           1 |         0.5 |
| 2020-05-14 00:00:00 |           5 |         2.5 |
| 2020-05-15 00:00:00 |           1 |         0.5 |
| 2020-05-16 00:00:00 |           9 |         4.5 |

# verify datetime format and set index
df.date = pd.to_datetime(df.date)
df.set_index('date', inplace=True)

變換DataFrame

使用.stack

  • 需要此轉換才能從 seaborn 獲得所需的 plot
df1 = df.stack().reset_index().set_index('date').rename(columns={'level_1': 'Status', 0: 'Values'})

使用.melt

df1 = df.melt(ignore_index=False, var_name='Status', value_name='Values')

轉換結果

               Status  Values
date                         
2022-06-24  Confirmed     2.0
2022-06-25  Confirmed     4.0
2022-06-26  Confirmed     1.0
2022-06-27  Confirmed     5.0
2022-06-28  Confirmed     2.0

Seaborn plot

  • 格式化 x 軸刻度標簽需要使用df而不是df1 如上所示,每個日期都重復,因此df1.index.to_series()將生成一個包含重復日期的列表。
ax = sns.barplot(x=df1.index, y='Values', data=df1, hue='Status')

# format the x-axis tick labels uses df, not df1
ax.xaxis.set_major_formatter(plt.FixedFormatter(df.index.to_series().dt.strftime("%Y-%m-%d")))

# alternative use the following to format the labels
# _, labels = plt.xticks()
# labels = [label.get_text()[:10] for label in labels]
# ax.xaxis.set_major_formatter(plt.FixedFormatter(labels))

plt.xticks(rotation=90)
plt.show()

或者df.plot.bar()

  • 生成與上面相同的圖形,但不轉換為df1
  • df有一個日期時間索引,它被識別為 x 軸,所有列都繪制在 y 軸上。
ax = df.plot.bar()
ax.xaxis.set_major_formatter(plt.FixedFormatter(df.index.to_series().dt.strftime("%Y-%m-%d")))
plt.show()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM