Reputation: 11679
I am generating horizontal bar graphs using mathplotlib from
SO: How to plot multiple horizontal bars in one chart with matplotlib. The problem is when I have more than 2 horizontal bars, the bars are getting overlapped. Not sure, what I am doing wrong.
Here is the following graph code
import pandas
import matplotlib.pyplot as plt
import numpy as np
df = pandas.DataFrame(dict(graph=['q1','q2','q3' , 'q4','q5',' q6'],
n=[3, 5, 2,3 ,5 , 2], m=[6, 1, 3, 6 , 1 , 3]))
ind = np.arange(len(df))
width = 0.4
opacity = 0.4
fig, ax = plt.subplots()
ax.barh(ind, df.n, width, alpha=opacity, color='r', label='Existing')
ax.barh(ind + width, df.m, width, alpha=opacity,color='b', label='Community')
ax.barh(ind + 2* width, df.m, width, alpha=opacity,color='g', label='Robust')
ax.set(yticks=ind + width , yticklabels=df.graph, ylim=[2*width - 1, len(df)])
ax.legend()
#plt.xlabel('Queries')
plt.xlabel('Precesion')
plt.title('Precesion for these queries')
plt.show()
Currently, the graph looks like this
Upvotes: 0
Views: 3516
Reputation: 11
ax=df.plot.barh(width=0.85,figsize=(15,15))
adjust width(should be less than 1 otherwise overlaps) and figsize to get the best and clear view of bars. Because if the figure is bigger you can have a clear and bigger view of bars which is the ultimate goal.
Upvotes: 1
Reputation: 251598
You set the width of the bars to 0.4, but you have three bars in each group. That means the width of each group is 1.2. But you set the ticks only 1 unit apart, so your bars don't fit into the spaces.
Since you are using pandas, you don't really need to do all that. Just do df.plot(kind='barh')
and you will get a horizontal bar chart of the dataframe data. You can tweak the display colors, etc., by using various paramters to plot
that you can find in the documentation. (If you want the "graph" column to be used as y-axis labels, set it as the index: df.set_index('graph').plot(kind='barh')
)
(Using df.plot
will give a barplot with only two bars per group, since your DataFrame has only two numeric columns. In your example, you plotted column m
twice, which doesn't seem very useful. If you really want to do that, you could add a duplicate column into the DataFrame.)
Upvotes: 2