我想在堆叠的条形图中绘制不同组的采样数据。采样是在不同的千米处进行的。每个采样点之间的距离不相等。正常情况下,使用matplotlib.pyplot.bar或pandas.DataFrame.plot.bar进行绘制时,条形图会一一绘制在另一条上。它们的km值未在x轴上显示。如何在x轴上代表其km的位置绘制堆叠的条形图?
带有pandas.DataFrame.plot.bar
的标准条形图的代码:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame( {'Group 1': {-60.0:0, -20.0:0, 12.5:0, 62.0:0, 123.8:0, 181.0: 5.013532366071429e-06, 225.2: 0.00010224713604266826, 248.0: 0.0002520240051269531, 274.9: 0.0006304542296807856, 304.2: 0.0009587457616051962, 331.0: 0.0021422429744175505}, 'Group 2': {-60.0: 0.0003144776457026891, -20.0: 5.43150903588747e-05, 12.5: 0.00012757662141348495, 62.0: 6.852403753623154e-05, 123.8: 5.980538377849872e-05, 181.0: 5.000001780657088e-05, 225.2: 0.00010152032391840468, 248.0: 0.0005436288535458056, 274.9: 0.00038244130009346957, 304.2: 0.00023423789360943164, 331.0: 9.508221455006986e-05}, 'Group 3': {-60.0: 0.00021804919790451726, -20.0: 0.0002884471518114942, 12.5: 0.00024001954291413006, 62.0: 0.00020780311751064946, 123.8:0, 181.0: 0.0003548555407567293, 225.2: 0.0011448858440205976, 248.0: 0.0031436022397010425, 274.9: 0.001858462242669843, 304.2: 0.0019485330483867962, 331.0: 0.0017062062250634059}} )
ax = df.plot.bar(stacked=True)
ax.set_ylabel('TM [mg/l]')
ax.set_xlabel('km')
plt.tight_layout()
为清除:
标准条形图
我想要什么
答案 0 :(得分:2)
得到ImportanceOfBeingErnest的提示后,我使用matplotlib.pyplot.bar
而不是pandas.DataFrame.plot.bar
来获得想要的东西:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'Group 1': {-60.0:0, -20.0:0, 12.5:0, 62.0:0, 123.8:0, 181.0: 5.013532366071429e-06, 225.2: 0.00010224713604266826, 248.0: 0.0002520240051269531, 274.9: 0.0006304542296807856, 304.2: 0.0009587457616051962, 331.0: 0.0021422429744175505}, 'Group 2': {-60.0: 0.0003144776457026891, -20.0: 5.43150903588747e-05, 12.5: 0.00012757662141348495, 62.0: 6.852403753623154e-05, 123.8: 5.980538377849872e-05, 181.0: 5.000001780657088e-05, 225.2: 0.00010152032391840468, 248.0: 0.0005436288535458056, 274.9: 0.00038244130009346957, 304.2: 0.00023423789360943164, 331.0: 9.508221455006986e-05}, 'Group 3': {-60.0: 0.00021804919790451726, -20.0: 0.0002884471518114942, 12.5: 0.00024001954291413006, 62.0: 0.00020780311751064946, 123.8:0, 181.0: 0.0003548555407567293, 225.2: 0.0011448858440205976, 248.0: 0.0031436022397010425, 274.9: 0.001858462242669843, 304.2: 0.0019485330483867962, 331.0: 0.0017062062250634059}})
width = 15
bottom = 0
for i in df.columns:
plt.bar(df.index, df[i], width=width, bottom=bottom)
bottom += df[i]
plt.ylabel('TM [mg/l]')
plt.xlabel('km')
plt.legend(df.columns)
plt.tight_layout()
答案 1 :(得分:1)
您可以使用matplotlib中的pyplot.plot(data = df)函数(具有默认值)。它将自动格式化xticks。 否则,您可以尝试pyplot.xticks和pyplot.set_xticks来定制您的需求。