如何根据数据集平均值绘制条形图而不是 seaborn 中的默认 0 值?

How do I plot a barchart from the datasets mean value and not its default 0 value in seaborn?

我正在尝试绘制一个显示偏离均值的条形图。我查看了 seaborn 的文档,但还没有弄清楚如何绘制条形图,其中它的 y 轴从数据集的平均值开始而不是 0。本质上,我正在研究如何复制此图,但使用 seaborn .

示例数据集:

{'Year': {0: 2000, 1: 2001, 2: 2002, 3: 2003, 4: 2004, 5: 2005, 6: 2006, 7: 2007, 8: 2008, 9: 2009, 10:2010, 11: 2011, 12: 2012, 13: 2013, 14: 2014, 15: 2015, 16: 2016, 17: 2017, 18: 2018, 19:2019, 20: 2020}, 'Temperature (Degrees F)': {0: 64.87, 1:64.89, 2:65.55, 3:64.11, 4:61.63, 5:63.83, 6:63.46, 7:65.02, 8:63.3, 9:62.14, 10:64.86, 11:64.98, 12:66.25, 13:65.27, 14:63.49, 15:64.77, 16:64.49, 17:65.65, 18:64.8, 19:64.74, 20: 65.28}}

当前代码:

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

df_temp = pd.read_csv(r"C:\Users\rov\Desktop\CO\temp.csv", usecols=['Year', 'Temperature (Degrees F)'])

sns.set(style='darkgrid')
sns.set_context('talk')

fig, (ax1) = plt.subplots(nrows=1, figsize=(15,5))
sns.barplot(x='Year', y='Temperature (Degrees F)', data=df_temp, color='#3792CB', edgecolor= 'black', ax=ax1)

在内部,seaborn.barplot 调用 matplotlib.axes.Axes.bar,并且 seaborn.barplot 无法识别的任何关键字参数都传递给 matplotlib bar 方法(参见 the seaborn barplot documentation for more information ,特别是 **kwargs 参数)。

第二个函数有一个参数 bottom,它表示柱底部的 y 坐标(有关详细信息,请参阅 the matplotlib bar documentation)。您可以将此 bottom 参数设置为等于平均温度值。但是,条形高度是相对于底部确定的,因此您还应该从条形高度中减去平均温度值。下面给出了如何实现这一目标的一个示例。

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

df_temp = pd.read_csv("temp.csv", usecols=['Year', 'Temperature (Degrees F)'])

# calculate the mean temperature and subtract it from the dataset
mean = df_temp['Temperature (Degrees F)'].mean()
df_temp['Temperature (Degrees F)'] -= mean

sns.set(style='darkgrid')
sns.set_context('talk')

fig, (ax1) = plt.subplots(nrows=1, figsize=(15,5))
sns.barplot(x='Year', y='Temperature (Degrees F)', data=df_temp,
            color='#3792CB', edgecolor= 'black', ax=ax1,
            bottom=mean)  # <-- set the bottom of the bars