【问题标题】:scatter plots in seaborn/matplotlib with point size and color given by continuous dataframe columnseaborn/matplotlib 中的散点图,点大小和颜色由连续数据框列给出
【发布时间】:2017-08-02 22:15:44
【问题描述】:

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

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

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

seaborn/matplotlib 中的语法是什么?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

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

    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 表示点的面积。所以为了使直径与显示的数量成正比,它必须是平方的。

    【讨论】:

    • 谢谢。 ggplot 将连续数量映射到带有 bin 的离散图例。在matplotlib中没有办法做到这一点吗?绘图看起来也很不一样,是因为 matplotlib 对标记大小有奇怪的默认设置吗?
    • 这是可能的,但必须手动完成很多工作。请参阅更新的答案。标记大小看起来不同,因为我设置的不同。如答案中所述,我对值进行平方,以使标记的直径与显示的数量成正比。当然,您可以使用 s 参数设置任何其他大小。
    • 在 py 中有一个库可以让这更容易吗?这是很多复杂的代码。 seaborn 能做到吗?
    • Seaborn 没有这种开箱即用的图例。大多数时候,使用 seaborn 会使事情变得比纯 matplotlib 更复杂(我实际上只是在这里导入它来获取 iris 数据集,没有它我们可以摆脱这个 legend_handles_labels 的东西)。也就是说,我不知道提供此功能的其他库,但我也不是 plotly、bokeh、vispy 或任何其他工具的专家。
    • @jll :请参阅下面我使用 Altair 几行解决此问题的答案。
    【解决方案2】:

    下面是我使用Altair 解决这个问题的方法

    from altair import Chart
    import seaborn as sns
    iris = sns.load_dataset("iris")
    c = Chart(iris)
    c.mark_circle().encode(
        x='sepal_width',
        y='sepal_length',
        color='petal_length',
        size='petal_width',
    )
    

    对于这样的情节,Altair 可能是一个不错的选择。引用他们的网站:

    Altair 是一个基于 Vega-Lite 的 Python 声明性统计可视化库。借助 Altair,您可以花更多时间了解数据及其含义。

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 2017-11-22
      • 2015-05-28
      • 2019-11-23
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      相关资源
      最近更新 更多