Home > front end >  Plot multiple barchart in one chart
Plot multiple barchart in one chart

Time:08-24

I want to plot horizontal bar charts. If i add more than one bar chart (the commented out line in code) then it is overlayed, but i need to cut the x axies into multiple x axis. Here is my code so far and a sketch how it looks like now und how it should look like. I think the piece left is the cutting of the x axies but i cannot find it in official documentation.

df=pd.DataFrame()
df["yaxis"]=(9,10,22,24)
df["A"]=(0.3498,-0.46,0.38,0.9)
df["B"]=(0.85,-0.035,0.91,0)
df["C"]=(0,0.058,0.88,0)

len=df["yaxis"].size
fig, ax = plt.subplots()
ax.set_xlim(-3,3)
ax.set_yticks(range(len))
ax.set_yticklabels(df.yaxis)
ax.barh(range(len),df["A"].to_list(), color='r')
#ax.barh(range(len),df["B"].to_list(), color='g')
plt.axvline(x=0,color="black",linestyle='-')
plt.show()

enter image description here

CodePudding user response:

You can offset the position of the bars:

import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame()
df["yaxis"]=(9,10,22,24)
df["A"]=(0.3498,-0.46,0.38,0.9)
df["B"]=(0.85,-0.035,0.91,0)
df["C"]=(0,0.058,0.88,0)

n=df["yaxis"].size
height = 0.175
p1 = [t - height for t in range(n)]
p2 = [t for t in range(n)]
p3 = [t   height for t in range(n)]
fig, ax = plt.subplots()
ax.set_xlim(-3,3)
ax.set_yticks(range(len))
ax.set_yticklabels(df.yaxis)
ax.barh(p1,df["A"].to_list(), color='r', height=height, label="A")
ax.barh(p2,df["B"].to_list(), color='g', height=height, label="B")
ax.barh(p3,df["C"].to_list(), color='b', height=height, label="C")
ax.legend()
plt.axvline(x=0,color="black",linestyle='-')
plt.show()

enter image description here

  • Related