0

我正在尝试按照此处的演示:http: //blog.yhat.com/posts/aggregating-and-plotting-time-series-in-python.html 并且无法重现该图 图片

我的看起来像这样: 坏肉

我正在使用带有 Python 2.7 的 Win 8、来自 github 的最新 ggplot master(我认为是 0.6.6,但 pip 告诉我它是 0.6.5)、pandas 0.16.2、numpy 1.8.1 和 matplotlib 1.4.3。我想我已经正确地复制了演示中的代码:

import numpy as np
import pandas as pd
import matplotlib.pylab as plt
from ggplot import *

def floor_decade(date_value):
    "Takes a date. Returns the decade."
    return (date_value.year // 10) * 10

meat2 = meat.dropna(thresh=800, axis=1) # drop columns that have fewer than 800 observations
ts = meat2.set_index(['date'])

by_decade = ts.groupby(floor_decade).sum()

by_decade.index.name = 'year'

by_decade = by_decade.reset_index()

p1 = ggplot(by_decade, aes('year', weight='beef')) + \
    geom_bar() + \
    scale_y_continuous(labels='comma') + \
    ggtitle('Head of Cattle Slaughtered by Decade')

p1.draw()
plt.show()

by_decade_long = pd.melt(by_decade, id_vars="year")

p2 = ggplot(aes(x='year', weight='value', colour='variable'), data=by_decade_long) + \
geom_bar() + \
ggtitle("Meat Production by Decade")

p2.draw()
plt.show()
4

2 回答 2

1

你很亲密。尝试使用fill参数 inggplot而不是colour. 这将使用指定的颜色填充条的内部,而不是为线条着色。colour此外,您可以使用参数更改条形周围的线条geom_bar。以下显示了两者:

p2 = ggplot(aes(x='year', weight='value', fill='variable'), data=by_decade_long) + geom_bar(colour='black') + ggtitle("Meat Production by Decade")

条形图结果

资料来源:我刚刚经历了同样的努力学习 ggplot for python。

于 2016-01-06T04:23:46.807 回答
1

对我来说,这行不通。我仍然必须将参数 position='stack' 添加到 geom_bar(),所以geom_bar(position='stack')

ggplot(aes(x='year', weight='value', fill='variable'), data=by_decade_long) + \
geom_bar(position='stack') + \
ggtitle("Meat Production by Decade")

请注意,geom_bar(position='fill')您将获得相对分数,即百分比而不是值。

于 2017-04-19T07:29:28.913 回答