matplotlib 如何使用Pandas中的数据将时间序列线图转换为条形图?

zsbz8rwp  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(96)
  • 问题 *

我有一个包含3个子图的图,显示了两个数据集的结果。我希望子图A使用条形图,其他两个使用线条。我得到了所有三个子情节使用线,但我不能得到酒吧工作的子情节A,尽管摆弄了好几天。如果我使用Pandas内置的绘图函数df.plot(king=“bar”)而不是ax.plot,我会得到条形图,但这会破坏我的子绘图自定义,并且与绘图的其他部分不一致,所以如果可能的话,我想使用ax.plot。

代码(工作示例)

import pandas as pd 
import matplotlib.pyplot as plt
import numpy as np

data   = {}
dlist = ['Data 1', 'Data 2']
data['mean_1']=[0.5,-0.5,0.5,-0.5,0.5]
data[ 'std_1']=[0.2,-0.2,0.2,-0.2,0.2]
data['count_1']=[50,200,50,200,50]
data['mean_2']=[0.4,-0.4,0.4,-0.4,0.4]
data[ 'std_2']=[0.16,-0.16,0.16,-0.16,0.16]
data['count_2']=[70,160,40,240,40]

df         = pd.DataFrame.from_dict(data)
df['time'] = pd.date_range('2000-01-01 00:00:00','2000-01-02 00:00:00',freq='6H')
df         = df.set_index('time')
df

colors     = ['red', 'cornflowerblue']
mean_cols  = [col for col in df.columns if 'mean'  in col]
std_cols   = [col for col in df.columns if 'std'   in col]
count_cols = [col for col in df.columns if 'count' in col]

我使用www.example.com尝试了两种方法ax.bar,如下所示。第一个与子图B和C相同,但使用ax.bar而不是ax.plot。它给了我错误“TypeError:bar()缺少1个必需的位置参数:'height'“。我不知道如何引用“height”的dataframe。第二个将时间和y轴值转换为列表,并将它们用于ax.bar中的前两个参数。我得到“ValueError:too many values to unpack(expected 1)".条形图确实可以绘制,但它们与数据不匹配。

datelist = list(df.index.values)
col_list = df[df.columns[2]].values.tolist()

#Plot initialization
fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(8, 11))
start, end = '2000-01-01', '2000-01-02'
fig.suptitle('Stuff over Jan 1',fontsize=27,x=0.5)

#Subplot 1- Counts
i     = 0
for f in dlist:
    p,= ax1.plot(df.loc[start:end, count_cols[i]],color=colors[i])
#    p,= ax1.bar(df.loc[start:end, count_cols[i]],color=colors[i]) ##First solution##
#    p,= ax1.bar(datelist,col_list,color=colors[0]) ##Second solution##
    df[['count_'+str(i+1)]].plot(kind='bar',color=colors[i],alpha=0.5)
    i = i+1

#Subplot 2- Means
i = 0
for f in dlist:
    p,= ax2.plot(df.loc[start:end, mean_cols[i]],color=colors[i])
    i=i+1

#Subplot 3- Stan. Dev.
i = 0
for f in dlist:
    p,= ax3.plot(df.loc[start:end,std_cols[i]],color=colors[i])
    i=i+1

#Adjustments and save
fig.autofmt_xdate(rotation=0,ha='center')
plt.show()

问题

如何使用www.example.com或其他类似的ax方法将发布的图片中的线条变成条形ax.bar图?我不想使用pandas内置的绘图功能。

olmpazwi

olmpazwi1#

  • pandas.DataFrame.plot使用matplotlib作为默认后端。
  • 线图具有datetime的扩展位置,而条形图的扩展位置为0索引。
import pandas as pd
import matplotlib.pyplot as plt

# sample data
data =\
{pd.Timestamp('2000-01-01 00:00:00'): {'count_1': 50, 'count_2': 70, 'mean_1': 0.5, 'mean_2': 0.4, 'std_1': 0.2, 'std_2': 0.16},
 pd.Timestamp('2000-01-01 06:00:00'): {'count_1': 200, 'count_2': 160, 'mean_1': -0.5, 'mean_2': -0.4, 'std_1': -0.2, 'std_2': -0.16},
 pd.Timestamp('2000-01-01 12:00:00'): {'count_1': 50, 'count_2': 40, 'mean_1': 0.5, 'mean_2': 0.4, 'std_1': 0.2, 'std_2': 0.16},
 pd.Timestamp('2000-01-01 18:00:00'): {'count_1': 200, 'count_2': 240, 'mean_1': -0.5, 'mean_2': -0.4, 'std_1': -0.2, 'std_2': -0.16},
 pd.Timestamp('2000-01-02 00:00:00'): {'count_1': 50, 'count_2': 40, 'mean_1': 0.5, 'mean_2': 0.4, 'std_1': 0.2, 'std_2': 0.16}}

df = pd.DataFrame.from_dict(data, orient='index')

colors = ['red', 'cornflowerblue']

#Plot initialization
fig, axes = plt.subplots(3, figsize=(8, 11), sharex=False, tight_layout=True)
axes = axes.flat
fig.suptitle('Stuff over Jan 1', fontsize=27, x=0.5)

# add a H:M time column for the bar x-axis
df = df.assign(time=df.index.strftime('%H:%M'))

# plot the dataframe columns directly to the assigned axes
df.plot(kind='bar', x='time', y=['count_1', 'count_2'], color=colors, rot=0, alpha=0.5, ax=axes[0])
df.plot(y=['mean_1', 'mean_2'], color=colors, alpha=0.5, rot=0, ax=axes[1])
df.plot(y=['std_1', 'std_2'], color=colors, alpha=0.5, rot=0, ax=axes[2])

# move the legends
for ax in axes:
    ax.legend(bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)

plt.show()

相关问题