python - 使用 Seaborn 绘图

标签 python pandas matplotlib seaborn

我只是想知道如何在 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
...

我想绘制的条形图:

enter image description here

如果有人知道如何使用 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()

enter image description here

该过程可以增加到包括所有 12 个月,但我不知道有哪个代码可以在不操作数据的情况下完成此操作。

关于python - 使用 Seaborn 绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33524694/

相关文章:

python - 段错误 : 11 when importing math into Python

python - 获取列表长度的特定百分比的索引

python - 用 Pandas 延迟加载 csv

python - 将文本标签放置在不依赖于数据的 3D 坐标中

matplotlib - 在 matplotlib 中用圆裁剪三角形

python - 使用固定宽度的行编写/解析文本文件

python - 使用 reduce 和装饰器在 Python 中级联函数

python - 如何在计算中直接使用 Pandas Date-time 索引?

python - Pandas – 创建缓冲列

python - 使用 plt 在热图上绘制梯度箭头