Reputation: 852
I would like to have a step-wise area plot in matplotib with pandas. I adjusted the code for a step-wise line plot but I get an error message. Here is the current code:
import pandas as pd
from matplotlib import pyplot as plt
%matplotlib inline
columns = ['Conventional control', 'Optimized control']
power_values = [[0.73,1.28],
[0.21, 0.21],
[0.18, 0.18],
[0.16, 1.00],
[0.57, 0.76],
[1.63, 1.62],
[3.28, 2.77],
[3.92, 0.47],
[3.29, 0.51],
[2.01, 3.64],
[1.72, 4.45],
[2.2, 0.59],
[2.33, 4.34],
[2.01, 2.05],
[1.39, 1.68],
[2.06, 0.55],
[3.07, 0.61],
[4.07, 0.61],
[3.66, 0.59],
[2.67, 0.59] ,
[1.54, 1.65],
[1.37, 1.55],
[1.36, 0.95],
[1.1, 1.70],
[0,0]]
wind_data = pd.DataFrame(power_values, index=range(0, 25), columns=columns)
fig = plt.figure(linewidth=1, figsize=(9, 5))
ax = wind_data.plot.area(ax=plt.gca(), color =["saddlebrown", "limegreen"], stacked=False, drawstyle="steps-post" )
ax.set_facecolor("white")
ax.set_xlabel("Time of day", fontsize = 14, labelpad=8)
ax.set_ylabel("Electrical power in kW", fontsize = 14,labelpad=8)
ax.set_xlim(0, 24)
ax.set_ylim(0, 5)
plt.xticks(wind_data.index, labels=[f'{h:02d}:00' for h in wind_data.index], rotation=90)
plt.grid(axis='y', alpha=.4)
plt.tight_layout()
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"]
ax.tick_params(axis='both', which='major', labelsize=14)
ax.legend(loc='center left', bbox_to_anchor=(0.15, 1.07), fontsize = 14, ncol=3)
plt.savefig('CS_Cost_PerTimeslot.png', edgecolor='black', dpi=400, bbox_inches='tight')
plt.show()
If I do not use the argument "drawstyle="steps-post" I get just an normal area plot. But I would like to have a step-wise area plot. When using this attribut (as with the line plot) I get the error message:" AttributeError: 'PolyCollection' object has no property 'drawstyle' ". I'd be very happy if someone could help me on that. Maybe there is also another way how to tell matpoltlib not to linearly interpolate the lines between the data points.
Upvotes: 1
Views: 624
Reputation: 4800
I think the simplest way to solve your problem is to use the pyplot fill_between
command directly. That way you get superb control over all the plotting elements you might want. Slightly less user friendly than the DataFrame.plot
api, but still good.
Replace the line
ax = wind_data.plot.area(ax=plt.gca(), color =["saddlebrown", "limegreen"], stacked=False,drawstyle="steps-post")
with
ax=plt.gca()
for column,color in zip(wind_data.columns,['saddlebrown','limegreen']):
ax.fill_between(
x=wind_data.index,
y1=wind_data[column],
y2=0,
label=column,
color=color,
alpha=.5,
step='post',
linewidth=2,
)
and you're good.
Upvotes: 2