Python matplotlib中的分步直线图

Python matplotlib中的分步直线图,python,matplotlib,Python,Matplotlib,我想在Matplotlib中有一个分步直线图。线条的形状应与此相似(参见屏幕截图): 这是我当前的代码: import pandas as pd from matplotlib import pyplot as plt %matplotlib inline prices = [12.05, 17.69, 15.31, 12.75, 17.18, 25.05, 33.19, 38.56, 42.9, 38.29, 37.06, 38.94, 36.36, 39.45, 43.97, 46.1

我想在Matplotlib中有一个分步直线图。线条的形状应与此相似(参见屏幕截图):

这是我当前的代码:

import pandas as pd
from matplotlib import pyplot as plt
%matplotlib inline


prices = [12.05, 17.69, 15.31, 12.75, 17.18, 25.05, 33.19, 38.56, 42.9, 38.29, 37.06, 38.94, 36.36, 39.45, 43.97, 46.14, 50.96, 51.04, 48.85, 45.6, 42.38, 39.83, 33.53, 30.03, 28.69
]


price_data = pd.DataFrame(prices, index=range(0, 25))
fig = plt.figure(linewidth=1, figsize=(7, 5))
ax = price_data.plot.line(ax=plt.gca(), color="green"  )
ax.set_facecolor("white")
ax.set_xlabel("Time of day", fontsize = 14, labelpad=8)
ax.set_ylabel("Price in €/MWh", fontsize = 14,labelpad=8)
ax.set_xlim(0, 24)
ax.set_ylim(0, 60)


plt.xticks(price_data.index, labels=[f'{h:02d}:00' for h in price_data.index], rotation=90)
plt.grid(axis='y', alpha=.4)
plt.tight_layout()
xticks = ['00:00', '01:00', '02:00' , '03:00', '04:00' , '05:00' , '06:00' , '07:00' , '08:00' , 
          '09:00' , '10:00' , '11:00' , '12:00' , '13:00' , '14:00' , '15:00' , '16:00' 
          , '17:00', '18:00', '19:00' , '20:00' , '21:00', '22:00' , '23:00' , '24:00'  ]
xvals = [0, 1*12, 2*12, 3*12, 4*12, 5*12, 6*12, 7*12, 8*12, 9*12, 10*12, 11*12, 12*12, 13*12, 14*12, 15*12, 16*12
        , 17*12, 18*12, 19*12, 20*12, 21*12, 22*12, 23*12, 24*12] 
ax.set(xticks=xvals, xticklabels=xticks)
ax.tick_params(axis='both', which='major', labelsize=14)
ax.legend(loc='center left', bbox_to_anchor=(0.03, 1.15), fontsize = 14, ncol=3)
plt.savefig('Prices.png', edgecolor='black', dpi=300, bbox_inches='tight')
plt.show()
这是我当前的输出(见屏幕截图):
[

您只需在绘图上使用
step
功能,使用x和y值,如
plt.step(xvals,prices)
在定义了xVAL之后,只需添加这一行就可以为您提供一个良好的起点

有关更多详细信息,请参阅:


使用@JohanC的精彩评论,这里有一个解决方案

正如他所说的,摆脱
xticks
xvals
,等等。你已经用
plt.xticks(price_data.index,labels=[f'{h:02d}:00'表示price_data.index中的h],rotation=90)正确地定义了你的刻度,而且你不必自己键入24个不同的值

要获得类似于步骤的绘图,只需将参数
drawstyle=“steps pre”
“steps post”
(或中的其他选项)添加到绘图函数中

from matplotlib import pyplot as plt
%matplotlib inline

prices = [12.05, 17.69, 15.31, 12.75, 17.18, 25.05, 33.19, 38.56, 42.9, 38.29, 37.06, 38.94, 36.36, 39.45, 43.97, 46.14, 50.96, 51.04, 48.85, 45.6, 42.38, 39.83, 33.53, 30.03, 28.69]    
hours = list(range(25)) # [0, 1, 2, ... 22, 23, 24]
labels = [f'{h:02d}:00' for h in hours] # ["00:00", "01:00", ... "23:00", "24:00"]

fig = plt.figure(linewidth=1, figsize=(7, 5))
ax = plt.gca()

ax.plot(hours, prices, color="green", drawstyle="steps-post") # <- drawstyle argument.
ax.set_xlabel("Time of day", fontsize=14, labelpad=8)
ax.set_ylabel("Price in €/MWh", fontsize=14, labelpad=8)
ax.set_xlim(0, 24)
ax.set_ylim(0, 60)    
plt.xticks(hours, labels=labels, rotation=90)
plt.grid(axis='y', alpha=.4)
ax.tick_params(axis='both', which='major', labelsize=14)
# (Optional) ax.legend(loc='center left', bbox_to_anchor=(0.03, 1.15), fontsize = 14, ncol=3)
plt.tight_layout() # This must be called last, after all elements (plot and legend) are ready.
plt.savefig('Prices.png', edgecolor='black', dpi=300, bbox_inches='tight')
plt.show()
从matplotlib导入pyplot作为plt
%matplotlib内联
价格=[12.05,17.69,15.31,12.75,17.18,25.05,33.19,38.56,42.9,38.29,37.06,38.94,36.36,39.45,43.97,46.14,50.96,51.04,48.85,45.6,42.38,39.83,33.53,30.03,28.69]
小时=列表(范围(25))#[0,1,2,…22,23,24]
labels=[f'{h:02d}:00'表示小时数]#[“00:00”、“01:00”、…“23:00”、“24:00”]
图=plt.图(线宽=1,图尺寸=(7,5))
ax=plt.gca()

ax.plot(hours,prices,color=“green”,drawstyle=“steps post”)#什么是风数据
?谢谢你的评论Guimoute。这是我的错误。它应该是价格数据。但该图看起来并不像预期的那样,将所有小时乘以12没有任何意义。只需省略
ax.set(xticks=xvals,xticklabels=xticks)
因为它将所有刻度放在了错误的位置。刻度已经通过
plt.xticks(..)
正确放置。感谢您的评论JohanC。在下面来自用户10455554的回答中,小时数也是multiplied@PeterBe不要麻烦自己键入序列。例如,
labels=[f'{h:02d}:00'代表price_data.index中的h]
很棒。您可以执行
xvals=list(范围(0,25))
。现在JohanC是对的,你不需要
xVAL
xticks
。感谢用户104554的回答和帮助。绘图看起来不错。但是我怎样才能去掉绿线和上面的图例呢?好的,Guimoute速度更快,绿线是pandas.dataframe
price\u data.plot.line(ax=plt.gca(),color)中的绘图=“绿色”)
我添加了另一行matplotlib step函数,而不是使用
drawstyle
参数,这是更好的解决方案。感谢您的回答。我如何摆脱图例?只需删除“ax.legend(loc='center left',bbox_to_anchor=(0.03,1.15),fontsize=14,ncol=3)“只是导致出现在右上角的图例,这可能是由于Panda处理事情的方式。如果我们使用
ax.plot(x,y)
并删除
ax.legend(…)
,它确实会消失。我将编辑.Thaks Guimoute以供您评论。不幸的是,我在使用您编辑的代码时出错。”“TypeError:plot得到了一个意外的关键字参数‘x’”@PeterBe啊我想实际上根本不需要
x=
y=
!非常感谢您的帮助和努力
from matplotlib import pyplot as plt
%matplotlib inline

prices = [12.05, 17.69, 15.31, 12.75, 17.18, 25.05, 33.19, 38.56, 42.9, 38.29, 37.06, 38.94, 36.36, 39.45, 43.97, 46.14, 50.96, 51.04, 48.85, 45.6, 42.38, 39.83, 33.53, 30.03, 28.69]    
hours = list(range(25)) # [0, 1, 2, ... 22, 23, 24]
labels = [f'{h:02d}:00' for h in hours] # ["00:00", "01:00", ... "23:00", "24:00"]

fig = plt.figure(linewidth=1, figsize=(7, 5))
ax = plt.gca()

ax.plot(hours, prices, color="green", drawstyle="steps-post") # <- drawstyle argument.
ax.set_xlabel("Time of day", fontsize=14, labelpad=8)
ax.set_ylabel("Price in €/MWh", fontsize=14, labelpad=8)
ax.set_xlim(0, 24)
ax.set_ylim(0, 60)    
plt.xticks(hours, labels=labels, rotation=90)
plt.grid(axis='y', alpha=.4)
ax.tick_params(axis='both', which='major', labelsize=14)
# (Optional) ax.legend(loc='center left', bbox_to_anchor=(0.03, 1.15), fontsize = 14, ncol=3)
plt.tight_layout() # This must be called last, after all elements (plot and legend) are ready.
plt.savefig('Prices.png', edgecolor='black', dpi=300, bbox_inches='tight')
plt.show()