Home > database >  Stacked barplot with repeated colors by value and fixed length for each bin
Stacked barplot with repeated colors by value and fixed length for each bin

Time:11-16

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)

first try

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)}])

second try

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

  1. How do I do that?
  2. Is there a better way to generate such a plot?
  3. Is there a specific name for such a plot?
  4. Instead of fixed colors per value, is it possible to use a color scale?
  5. 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:

enter image description here

  • Related