如何控制海洋条形图中的条之间的空白?

时间:2020-07-24 10:14:31

标签: python bar-chart seaborn

我有以下简单的示例数据框:

import pandas as pd
data = [['Alex',25],['Bob',34],['Sofia',26],["Claire",35]]
df = pd.DataFrame(data,columns=['Name','Age'])
df["sex"]=["male","male","female","female"]

我使用以下代码绘制条形图:

import matplotlib.pyplot as plt

import seaborn as sns

age_plot=sns.barplot(data=df,x="Name",y="Age", hue="sex",dodge=False)
age_plot.get_legend().remove()
plt.setp(age_plot.get_xticklabels(), rotation=90)
plt.ylim(0,40)
age_plot.tick_params(labelsize=14)
age_plot.set_ylabel("Age",fontsize=15)
age_plot.set_xlabel("",fontsize=1)
plt.tight_layout()

产生以下条形图:

enter image description here

我的问题:如何控制条之间的空白?我想要在男性(蓝色)和女性(橙色)条之间留出一些空白。

输出应如下所示(在MS PPT中进行了错误的编辑):

enter image description here

我在matplotplib上找到了几个主题(例如,https://python-graph-gallery.com/5-control-width-and-space-in-barplots/),但没有找到{{ 1}}。我更喜欢使用seaborn,因为seaborn上色的功能很简单。

谢谢。

1 个答案:

答案 0 :(得分:2)

一种可能是在中间插入一个空栏:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({'Name': ['Alex', 'Bob', 'Sofia', 'Claire'], 'Age': [15, 18, 16, 22], 'Gender': ['M', 'M', 'F', 'F']})
df = pd.concat([df[df.Gender == 'M'], pd.DataFrame({'Name': [''], 'Age': [0], 'Gender': ['M']}), df[df.Gender == 'F']])

age_plot = sns.barplot(data=df, x="Name", y="Age", hue="Gender", dodge=False)
age_plot.get_legend().remove()
plt.setp(age_plot.get_xticklabels(), rotation=90)
plt.ylim(0, 40)
age_plot.tick_params(labelsize=14)
age_plot.tick_params(length=0, axis='x')
age_plot.set_ylabel("Age", fontsize=15)
age_plot.set_xlabel("", fontsize=1)
plt.tight_layout()
plt.show()

example plot