2013-10-15 20 views
8

我試圖在使用Python ipython notebookggplot for python數字的簡單列表的直方圖。使用pylab,這很容易,但我不能讓ggplot工作。如何使IPython的筆記本使用GGPLOT2(對於Python)直方圖

我使用這個代碼(基於鑽石直方圖例如,不工作對我來說):

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") 

使用IPython的& pylab,我可以只用hist(a)直方圖並顯示。如何使用ggplot創建直方圖?

+0

你想ggplot因爲風格還是有其他原因。如果前者是這種情況,你可以試試mpltools,一個可以模仿ggplot風格的matplotlib擴展(請參閱http://tonysyu.github.io/mpltools/auto_examples/style/plot_ggplot.html) – Jakob

+0

我最想使用ggplot,因爲它看起來很有趣。 – Rory

回答

17

如果您只想製作矢量'a'中數字的直方圖,則會出現一些問題。

首先,ggplot以pandas Dataframe的形式接受數據,所以您需要先構建它。

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

其次,GEOM是geom_histogram()geom_hist()。最後,它看起來像是從鑽石數據的一個示例圖中投入代碼。你不需要那個,所以我把它刪除了。

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

enter image description here

7

你有沒有在你的筆記本添加

%matplotlib inline

的第一個命令?

相關問題