如何使用seaborn制作气泡图

2024-10-06 11:27:33 发布

您现在位置:Python中文网/ 问答频道 /正文

   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


Tags: importnumpydatamatplotlibasnppltseaborn
2条回答

您可以针对您的问题尝试此代码段

-我修改了您的数据格式,建议您使用熊猫作为 数据可视化。

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

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

# data
x=["IEEE", "Elsevier", "Others", "IEEE", "Elsevier", "Others"]
y=[7, 6, 2, 5, 4, 3]
z=["conference", "journal", "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 ^{}^{}(或sns.catplot(kind=strip or kind=swarm))提供了方便的dodge参数,防止气泡重叠。唯一的缺点是size参数将单个大小应用于所有气泡,而sizes参数(在另一个答案中使用)在这里没有用处。它们不像^{}ssize参数那样工作。因此,生成绘图后,必须编辑每个气泡的大小:

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);

stripplot


或者,您可以将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

scatterplot




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

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

balloon plot(又称分类气泡图):

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

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

相关问题 更多 >