Skip to main content
 首页 » 编程设计

python之使用 Seaborn 绘图

2024年10月24日11zhwl

我只是想知道如何在 Seaborn 中绘制这种图表和数据:

数据.csv:

1,2,3 
2007,05,06 
2007,05,06 
2007,05,08 
2007,05,08 
2007,05,12 
2007,05,15 
2007,05,16 
... 

我想绘制的条形图:

如果有人知道如何使用 Seaborn 使用我的数据绘制这种条形图,我将不胜感激。

请您参考如下方法:

根据您提供的数据,无法创建绘图,因此我制作了一个小样本来对其进行测试。它有点长,因为您需要操作数据。主要思想是了解堆叠条形图是加法规则条形图。

import pandas as pd 
import io 
import matplotlib.pyplot as plt 
import seaborn as sns 
 
# sample data - 3rd column ignored 
data = """ 
year,month,count 
2007,05,06 
2007,05,06 
2007,06,08 
2007,06,08 
2008,05,12 
2008,05,15 
2008,06,16 
    """ 
# read data 
df = pd.read_csv(io.StringIO(data), delimiter=',') 
 
groups = df.groupby(['year','month']) 
plot_data = groups.count() # obtain count of year and month multi-index 
 
# additive barplot (May and June) 
sns.barplot(x = plot_data.reset_index(level=1).index.unique(), y = plot_data.sum(axis=0, level=1)['count'], data=df , color = "red", ci=None) 
# single bottom plot (in this case May only or "05") 
bottom_plot = sns.barplot(x = plot_data.reset_index(level=1).index.unique(), y = plot_data.reorder_levels(['month','year']).loc[5]['count'], color = "#0000A3") 
 
bottom_plot.set_ylabel("Count") 
bottom_plot.set_xlabel("Year") 
 
plt.show() 

这个过程可以增加到包括所有 12 个月,但我不知道有一个代码可以在不处理数据的情况下做到这一点。