How to make a histogram in ipython notebook using ggplot2 (for python)

时光怂恿深爱的人放手 提交于 2019-12-04 11:00:17

问题


I'm trying to make a histogram of a simple list of numbers in python using ipython notebook and ggplot for python. Using pylab, it's easy enough, but I cannot get ggplot to work.

I'm using this code (based on the diamond histogram example, which does work for me):

from ggplot import *
a = [1, 1, 2, 1, 1, 4, 5, 6]
p = ggplot(aes(x='carat'), data=a)
p + geom_hist() + ggtitle("Histogram of Diamond Carats") + labs("Carats", "Freq")

Using ipython & pylab, I can make a histogram with just hist(a) and it displays. How do I make a histogram come up using ggplot?


回答1:


If you just want to make a histogram of the numbers in your vector 'a', there are a couple of problems.

First, ggplot accepts data in the form of a pandas Dataframe, so you need to build that first.

import pandas as pd
a = [1, 1, 2, 1, 1, 4, 5, 6]
df = pd.DataFrame(a, columns=['a'])

Second, the geom is geom_histogram() not geom_hist(). And finally, it looks like you're throwing in code from one of the example plots of the diamond data. You don't need that, so I've removed it.

from ggplot import *
p = ggplot(aes(x='a'), data=df)
p + geom_histogram(binwidth=1)




回答2:


Did you add

%matplotlib inline

as first command in your notebook?



来源:https://stackoverflow.com/questions/19377371/how-to-make-a-histogram-in-ipython-notebook-using-ggplot2-for-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!