mati
mati

Reputation: 1145

How to create an unequally spaced bar chart?

Using plot.barh creates a bar chart with equally spaced columns. However, I have a column with unequally spaced values (df1['dist']) which I would like to use in the plot to provide additional information:

df1 = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b'])
df1['dist'] = pd.Series([1,5,6.5,15,45], index=df1.index)

df1.plot.barh(['dist'],['a','b'],stacked=True, width=.6, color = ['y','b'])
plt.show()

Is that possible?

Upvotes: 0

Views: 136

Answers (1)

Thomas Kühn
Thomas Kühn

Reputation: 9830

You can create the bar chart 'by hand' using the barh function from matplotlib:

import pandas as pd
from matplotlib import pyplot as plt
import numpy as np

df1 = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b'])
df1['dist'] = pd.Series([1,5,6.5,15,45], index=df1.index)

fig,ax = plt.subplots()

ax.barh(df1['dist'],df1['a'],height =1)
ax.barh(df1['dist'],df1['b'],left=df1['a'], height =1)
plt.show()

Here is the result:

enter image description here

I'm not sure if this actually looks better, as now the bars are quite thin. However, you can adjust them with the height parameter.

Upvotes: 2

Related Questions