I have a DataFrame with 10 columns and three values {0,1,2}:
row1 = [random.randint(0,2) for i in range(10)]
row2 = [random.randint(0,2) for i in range(10)]
df = pd.DataFrame([{i:row1[i] for i in range(10)}, {i:row2[i] for i in range(10)}])
I want to plot these values in a horizonal barplot, where each value should have another color, but the same width.
First try
df.plot(kind='barh', stacked=True, legend=False)
ok, so here the width of each stacked value is not fixed. So I thought of a helper Dataframe which fixes the width to one:
df2 = pd.DataFrame([{i:1 for i in range(10)}, {i:1 for i in range(10)}])
ok, perfect, each stacked column has the same width, but now I want the colors to be either grey, blue or red, according to the values in df
- How do I do that?
- Is there a better way to generate such a plot?
- Is there a specific name for such a plot?
- Instead of fixed colors per value, is it possible to use a color scale?
- Bonus: Is there a way to frame each bin? So that if two bins (columns in a row) have the same value next to each other, you can still see these are two separate datapoints?
CodePudding user response:
I think you are searching for plt.imshow
or sns.heatmap
rather than stack barplot. For example:
sns.heatmap(df, cmap='tab10', linewidths=1, linecolor='w')
gives: