如何使用seaborn制作气泡图 如何创建具有正确气泡大小且没有重叠的图形

问题描述

   import matplotlib.pyplot as plt
    import numpy as np
    # data
    x=["IEEE","Elsevier","Others"]
    y=[7,6,2]
    import seaborn as sns
    plt.legend()
    plt.scatter(x,y,s=300,c="blue",alpha=0.4,linewidth=3)
    plt.ylabel("No. of Papers")
    plt.figure(figsize=(10,4)) 

我想制作如图所示的图表。我不确定如何为期刊和会议类别提供数据。 (目前,我只包括一个)。另外,我不确定如何为每个类别添加不同的颜色。

bubble chart

解决方法

你可以试试这个代码片段来解决你的问题。

- 我修改了你的数据格式,我建议你使用pandas 数据可视化。

- 我又添加了一个字段以更有效地可视化数据。

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

# data
x=["IEEE","Elsevier","Others","IEEE","Others"]
y=[7,6,2,5,4,3]
z=["conference","journal","conference","journal"]

# create pandas dataframe
data_list = pd.DataFrame(
    {'x_axis': x,'y_axis': y,'category': z
    })

# change size of data points
minsize = min(data_list['y_axis'])
maxsize = max(data_list['y_axis'])

# scatter plot
sns.catplot(x="x_axis",y="y_axis",kind="swarm",hue="category",sizes=(minsize*100,maxsize*100),data=data_list)
plt.grid()

OUTPUT:

,

如何创建具有正确气泡大小且没有重叠的图形

Seaborn stripplotswarmplot(或 sns.catplot(kind=strip or kind=swarm))提供了方便的 dodge 参数,可防止气泡重叠。唯一的缺点是 size 参数对所有气泡应用单一大小,而 sizes 参数(如其他答案中使用的)在这里没有用。它们不像 scatterplotssize 参数那样工作。因此,必须在生成绘图后编辑每个气泡的大小:

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','Others']
y = np.array([7,3,7,1,3])
z = ['conference','conference','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',alpha=0.2)
ax.spines['bottom'].set(position='zero',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',length=25,width=0.8,color=[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',size=12)
ax.legend(bbox_to_anchor=(1.0,0.5),loc='center left',frameon=False);

stripplot


或者,您可以将 scatterplot 与方便的 s 参数(或 size)一起使用,然后编辑气泡之间的空间以重现缺少 dodge 的效果参数(注意 x_jitter 参数似乎没有效果)。这是一个使用与之前相同的数据且没有所有额外格式的示例:

# Create seaborn scatterplot with size argument
ax = sns.scatterplot(data=df,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

scatterplot




作为旁注,我建议您考虑使用其他类型的数据绘图。分组条形图:

df.pivot(index='organisation',columns='category').plot.bar()

或者一个 balloon plot(又名分类气泡图):

sns.scatterplot(data=df,y='category',s=100*count).margins(0.4)

为什么?在气泡图中,计数使用 2 个视觉属性显示,i) y 坐标位置和 ii) 气泡大小。只有其中一个是真正必要的。