为ggPlot线图创建Pandas DataFrame

2 投票
1 回答
4777 浏览
提问于 2025-04-18 16:06

我正在尝试创建一个Pandas数据框,这样我就可以用ggPlot来做一些可视化的图表。但是我在设置数据框的结构时遇到了困难。

我想要的可视化是一个线图,显示的是年份和总数的关系。这个线图会跟踪多种“死亡原因”在不同年份的变化。

我已经导入了我的CSV文件,并按年份和“死亡原因”进行了分组,然后进行了计数。但是现在的格式不适合创建线图,因为它还不是一个数据框。

下面是我的代码,任何建议都很有帮助,谢谢。

我想从CSV文件中提取的字段是“死亡年份”和“死亡原因”。

from pandas import * 
from ggplot import *

df = pandas.read_csv('query_result.csv')

newDF = df.loc[:,['date_of_death_year','acme_underlying_cause_code']]
data = DataFrame(newDF.groupby(['date_of_death_year','acme_underlying_cause_code']).size())

print data

1 个回答

1

这个问题已经很久了,但其实解决起来很简单。(提示一下,这和 ggplot 没关系,主要是关于 pandas 的用法)

下面是我会如何处理你的代码:

import numpy as np   # |Don't import * from these
import pandas as pd  # |
from ggplot import * # But this is customary because it's like R

# All this bit is just to make a DataFrame
# You can ignore it all
causes = ['foo', 'bar', 'baz']
years = [2001, 2002, 2003, 2004]
size = 100
data = {'causes':np.random.choice(causes, size),
        'years':np.random.choice(years, size),
        'something_else':np.random.random(size)
        }
df = pd.DataFrame(data)

# Here's where the good stuff happens. You're importing from
# a CSV so you can just start here
counts = df.groupby(['years', 'causes'])['something_else'].count()
counts = counts.reset_index() # Because ggplot doesn't plot with indexes
g = ggplot(counts, aes(x='years', y='something_else', color='causes')) +\
        geom_line()
print(g)

这样做的结果是:

ggplot multi line plot

撰写回答