-->

Align stacked bar charts usind pandas

2019-02-20 14:47发布

问题:

i'm trying to align all of the stacked bar charts having the same index. What's the best way doing this?stacked_bar_plots `

This is my code so far.

xantho99 = [545/60, 6/60, 1688/60, 44/60]
buch99 = [51/60, 2/60, 576/60, 7/60]
myco99 = [519/60, 9/60, 889/60, 28/60]
cory99 = [247/60, 5/60, 1160/60, 28/60]
xantho90 = [545/60, 8/60, 989/60, 27/60]
buch90 = [51/60, 3/60, 523/60, 5/60]
myco90 = [519/60, 11/60, 802/60, 32/60]
cory90 = [247/60, 7/60, 899/60, 27/60]
xanthouc = [545/60, 0/60, 5407/60, 193/60]
buchuc = [51/60, 0/60, 1014/60, 20/60]
mycouc = [519/60, 0/60, 4644/60, 101/60]
coryuc = [247/60, 0/60, 2384/60, 77/60]
df = pd.DataFrame([xantho, xantho99, xantho90, buch, buch99, buch90, myco, myco99, myco90, cory, cory99, cory90], columns=['Prodigal', 'Cd-hit', 'PSOT', 'Zusammenführen'], index=["X", "X","X", "B", "B","B", "M", "M","M", "C", "C","C"])
df.columns.name = "Abschnitt"
current_palette = "blue", "green", "red", "yellow"
ax = df.plot.bar(stacked=True, title="Zeitbedarf der einzelnen Abschnitte (Xanthomonas)", xlim=(0, sum(xantho)*1.1), color=current_palette, rot=0)
ax.set_xlabel("Zeit in Stunden")

Thank You!

回答1:

Here's the relevant code (should work if you put it at the bottom of the script in the question):

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
...
...
...
# Comment out old plot
# ax = df.plot.bar(stacked=True, title="Zeitbedarf der einzelnen Abschnitte (Xanthomonas)", xlim=(0, sum(xantho)*1.1), color=current_palette, rot=0)                                                         
# ax.set_xlabel("Zeit in Stunden")                                                                                                                   
spacing = [0, 0, 0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0]
p1 = plt.bar(np.arange(12) + spacing, df['Prodigal'], color="blue", width=1.0, edgecolor="black")
p2 = plt.bar(np.arange(12) + spacing, df['PSOT'], bottom=df['Prodigal'], color="red", width=1.0, edgecolor="black")
p3 = plt.bar(np.arange(12) + spacing, df['Zusammenführen'], bottom=df['Prodigal'] + df['PSOT'], color="yellow", width=1.0, edgecolor="black")
p4 = plt.bar(np.arange(12) + spacing, df['Cd-hit'], bottom=df['Prodigal'] + df['PSOT'] + df['Zusammenführen'], color="green", width=1.0, edgecolor="black")
plt.legend((p1[0], p2[0], p3[0], p4[0]), ('Prodigal', 'PSOT', 'Zusammenführen', 'Cd-hit'))
plt.show()

Here's what pops up after you run this snippet:

I think this is what's desired, based on our discussion in comments. HTH, let me know if this is what you were looking for!