如何创建具有正确气泡大小且没有重叠的图表
Seaborn stripplot 和 swarmplot(或 sns.catplot(kind=strip or kind=swarm))提供了方便的 dodge 参数,可以防止气泡重叠。唯一的缺点是 size 参数将单个大小应用于所有气泡,而 sizes 参数(在另一个答案中使用)在这里没有用。它们不像scatterplot 的s 和size 参数那样工作。因此,每个气泡的大小必须在生成绘图后进行编辑:
import numpy as np # v 1.19.2
import pandas as pd # v 1.1.3
import seaborn as sns # v 0.11.0
# Create sample data
x = ['IEEE', 'Elsevier', 'Others', 'IEEE', 'Elsevier', 'Others']
y = np.array([7, 6, 3, 7, 1, 3])
z = ['conference', 'conference', 'conference', 'journal', 'journal', 'journal']
df = pd.DataFrame(dict(organisation=x, count=y, category=z))
# Create seaborn stripplot (swarmplot can be used the same way)
ax = sns.stripplot(data=df, x='organisation', y='count', hue='category', dodge=True)
# Adjust the size of the bubbles
for coll in ax.collections[:-2]:
y = coll.get_offsets()[0][1]
coll.set_sizes([100*y])
# Format figure size, spines and grid
ax.figure.set_size_inches(7, 5)
ax.grid(axis='y', color='black', alpha=0.2)
ax.grid(axis='x', which='minor', color='black', alpha=0.2)
ax.spines['bottom'].set(position='zero', color='black', alpha=0.2)
sns.despine(left=True)
# Format ticks
ax.tick_params(axis='both', length=0, pad=10, labelsize=12)
ax.tick_params(axis='x', which='minor', length=25, width=0.8, color=[0, 0, 0, 0.2])
minor_xticks = [tick+0.5 for tick in ax.get_xticks() if tick != ax.get_xticks()[-1]]
ax.set_xticks(minor_xticks, minor=True)
ax.set_yticks(range(0, df['count'].max()+2))
# Edit labels and legend
ax.set_xlabel('Organisation', labelpad=15, size=12)
ax.set_ylabel('No. of Papers', labelpad=15, size=12)
ax.legend(bbox_to_anchor=(1.0, 0.5), loc='center left', frameon=False);
或者,您可以将scatterplot 与方便的s 参数(或size)一起使用,然后编辑气泡之间的空间以重现缺少dodge 参数的效果(请注意, x_jitter 参数似乎没有效果)。这是一个使用与以前相同的数据但没有所有额外格式的示例:
# Create seaborn scatterplot with size argument
ax = sns.scatterplot(data=df, x='organisation', y='count',
hue='category', s=100*df['count'])
ax.figure.set_size_inches(7, 5)
ax.margins(0.2)
# Dodge bubbles
bubbles = ax.collections[0].get_offsets()
signs = np.repeat([-1, 1], df['organisation'].nunique())
for bubble, sign in zip(bubbles, signs):
bubble[0] += sign*0.15
作为旁注,我建议您考虑为该数据绘制其他类型的图。分组条形图:
df.pivot(index='organisation', columns='category').plot.bar()
或者balloon plot(又名分类气泡图):
sns.scatterplot(data=df, x='organisation', y='category', s=100*count).margins(0.4)
为什么? 在气泡图中,计数使用 2 个视觉属性显示,i) y 坐标位置和 ii) 气泡大小。只有其中一个是真正需要的。