Vai*_*aro 6 python matplotlib bar-chart pandas
我想在堆积条形图中绘制不同组的采样数据。采样是在不同公里处进行的。每个采样点之间的距离不相等。通常,当使用 matplotlib.pyplot.bar 或 pandas.DataFrame.plot.bar 进行绘图时,条形图会一个接一个地绘制。它们的公里值未在 x 轴上表示。如何在 x 轴上代表公里位置处绘制堆积条形图?
标准条形图的代码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()
Run Code Online (Sandbox Code Playgroud)
清关:
标准条形图

我想要的是

在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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6261 次 |
| 最近记录: |