python - seaborn/matplotlib 中的散点图,点大小和颜色由连续数据框列给出

标签 python pandas matplotlib

我想在 seaborn/matplotlib 中绘制一个散点图,其中点的大小由数据框中的(连续)值决定,点的颜色也由数据框中另一列的连续值决定。在ggplot中,实现方式是:

ggplot(iris) + geom_point(aes(x=Sepal.Width, y=Sepal.Length, size=Petal.Width, color=Petal.Length))

enter image description here (这里的颜色/大小是连续的而不是分类值)

seaborn/matplotlib 中的语法是什么?

最佳答案

下面从问题中重现代码图。 获取图例有点麻烦,因为我们必须手动定义一些代理艺术家放入图例中,并删除通过 seaborn 样式生成的第一个自动图例条目。

enter image description here

import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")

plt.scatter(iris.sepal_width, iris.sepal_length, 
            c = iris.petal_length, s=(iris.petal_width**2)*60, cmap="viridis")
ax = plt.gca()

plt.colorbar(label="petal_length")
plt.xlabel("sepal_width")
plt.ylabel("sepal_length")

#make a legend:
pws = [0.5, 1, 1.5, 2., 2.5]
for pw in pws:
    plt.scatter([], [], s=(pw**2)*60, c="k",label=str(pw))

h, l = plt.gca().get_legend_handles_labels()
plt.legend(h[1:], l[1:], labelspacing=1.2, title="petal_width", borderpad=1, 
            frameon=True, framealpha=0.6, edgecolor="k", facecolor="w")

plt.show()

请注意,大小参数 s 表示点的面积。因此,为了使直径与要显示的数量成正比,必须对其进行平方。

关于python - seaborn/matplotlib 中的散点图,点大小和颜色由连续数据框列给出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42754458/

相关文章:

python - Pandas GroupBy 具有特殊总和

python - 为 Pandas 设置差异

python - Pandas 系列计数的适当功能

python - 如何在 Python 中创建白色图像?

python - 分配给无

python - Tensorflow官方MNIST模型训练精度高但预测性能低

python - Pandas 错误 : "pandas.hashtable.PyObjectHashTable.get_item"

python - 使用极投影将颜色条添加到 pcolormesh

python - 如何使用 pyplot.barh() 在每个条上显示条的值

python - 有没有办法像C#的 "with"一样使用Python "using"语句