【问题标题】:How to graph a seaborn lineplot more specifically如何更具体地绘制 seaborn 线图
【发布时间】:2021-07-16 07:27:45
【问题描述】:

给定一个海量 DataFrame df:

year        count
1980        -23
1980        -4
1981        10
1982        0
1982        4
...
2007        27
2008        0
2008        0
2009        -7
2009        5

值首先按year 排序,然后是count。 (显示的数值是任意变化的)

我想可视化count 如何随着year 的增加而不同地分布,这可以通过百分位图最有效地显示。但是,由于我的数据是在 DataFrame 中给出的,我认为更可行(坦率地说,更简单)的方法是使用seaborn.lineplot

import matplotlib.pyplot as plt
import seaborn as sns

fig, ax = plt.subplots(figsize=[16,12])

plt.axhline(y=0, color='black', linestyle='dotted')
sns.lineplot(x="year", y="count", ax=ax, data=df, color='red')

返回:

这个图表在某种程度上是有目的的,尽管我希望显示比单个百分位梯度具有更多的可变性。 (一个很好的例子是下图有 10 个百分位梯度,复制自此链接:Using percentiles of a timeseries to set colour gradient in Python's matplotlib

我想知道是否有办法使用seaborn.lineplot 实现如此详细的图形,如果没有,是否有办法从pandas DataFrame 数据中实现。

【问题讨论】:

    标签: python pandas seaborn


    【解决方案1】:

    一旦您生成了第一个置信区间或只生成了一条线,您就可以使用 matplotlib,如 post 所示,创建多个置信区间。

    另一种选择是使用sns.lineplot 在同一图形上绘图,尽管我认为 seaborn 不适合此。以数据集flights为例,首先绘制中值线或均值线:

    import seaborn as sns
    import matplotlib.pyplot as plt
    import numpy as np
    
    flights = sns.load_dataset("flights")
    fig,ax = plt.subplots(1,1)
    
    sns.lineplot(data=flights, x="year", y="passengers",ax=ax,ci=None,color="black")
    

    然后我们设置一个调色板并继续添加没有线条的波段(设置 linestyle = ''):

    cm = sns.color_palette("Blues",9)
    
    for ix,ci in enumerate(range(10,90,10)):
        sns.lineplot(data=flights, x="year", y="passengers",
                     ci = ci,
                     ax=ax,linestyle='',
                     hue = ci,palette={ci:cm[ix]})
    

    给出这样的东西:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 2021-04-26
      • 2019-02-05
      • 2017-11-17
      • 2021-09-29
      • 2021-11-23
      相关资源
      最近更新 更多