Home > Software engineering >  Matplotlip plot barchart of grouped data increase space of x-axis
Matplotlip plot barchart of grouped data increase space of x-axis

Time:08-24

I want to make a barchart out of gourped data, but I cannot get a space between the columns on x-axis. I tried to set different figure size and width set to 0.8 , but this does not help.

My code looks like this:

data = [['Tom', 'a'], ['Tom', 'a'],['nick', 'a'], ['juli', 'a'],['juli', 'a'],['juli', 'b'],['Simon', 'b'],['Tom', 'b'],['Sandra', 'a'],['Stefan', 'b'],['Johnny', 'a'],['Johnny', 'b'],['Johnny', 'b'],['Johnny', 'b']]
df = pd.DataFrame(data, columns=['name', 'category'])

ax= df.groupby('name')['category'].value_counts().unstack(0).plot(kind ="bar", width=1.0,figsize = (20, 8), align = 'center', color=['#F9986C', '#C9B265', 'blue', 'red', '#6ABFD0','#C4A5F6','yellow','#6BBCE5',
                                                                                                                               '#E791F6','maroon','green','indigo','teal','lime','darkslategrey','#B6B965','orange'])
plt.ylabel('Count',fontsize=23)
plt.xlabel('Category', fontsize=23)
plt.legend(bbox_to_anchor=(0.99, 0.99), loc='upper right', borderaxespad=0)
plt.show()

And outcome is: plot

Any suggestions?

CodePudding user response:

Changing the width of the individual bars in a group isn't currently supported. It also could be quite confusing to know which bars belong to the same group, especially with empty bars involved.

A simple workaround could be to set the edgecolor to ec='white' (and lw=1).

Or you could loop through the generated bars and update their width:

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

data = [['Tom', 'a'], ['Tom', 'a'],['nick', 'a'], ['juli', 'a'],['juli', 'a'],['juli', 'b'],['Simon', 'b'],['Tom', 'b'],['Sandra', 'a'],['Stefan', 'b'],['Johnny', 'a'],['Johnny', 'b'],['Johnny', 'b'],['Johnny', 'b']]
df = pd.DataFrame(data, columns=['name', 'category'])

ax = df.groupby('name')['category'].value_counts().unstack(0).plot(kind ="bar", width=1.0,figsize = (20, 8), align = 'center', color=['#F9986C', '#C9B265', 'blue', 'red', '#6ABFD0','#C4A5F6','yellow','#6BBCE5',

                                                                                                                              '#E791F6','maroon','green','indigo','teal','lime','darkslategrey','#B6B965','orange'])
ax.set_ylabel('Count',fontsize=23)
ax.set_xlabel('Category', fontsize=23)
ax.legend(bbox_to_anchor=(0.99, 0.99), loc='upper right', borderaxespad=0)

factor = 0.9  # reduce the width to 90% of their given width
for bars in ax.containers:
    for bar in bars:
        x, y = bar.get_xy()
        w = bar.get_width()
        bar.set_width(w * factor)
        bar.set_xy((x w * (1-factor)/2, y))

plt.tight_layout()
plt.show()

grouped bar plot, changing width of individual plots

  • Related