2016-10-08 30 views
2

我有這樣一個數據幀:如何用ggplot繪製一列數據框?

__________ 
| | sums | 
|---+------| 
| a | 122 | 
|---+------| 
| b | 23 | 
|---+------| 
| c | 321 | 
|__________| 

*通知 「A」, 「B」 和 「C」 的行名。

我希望看到這樣一個情節:

    ___ 
300 -|    | | 
200 -| ___  | | 
100 -| | | ___ | | 
    0 -|_|___|_|___|_|___|______ 
     a  b  c 

我怎樣才能做到呢?

回答

4

將rownames添加爲數據框中的列,然後繪圖。下面是使用內置的mtcars數據幀的例子:

library(tibble) 
library(ggplot2) 

ggplot(rownames_to_column(mtcars[1:3,], var="Model"), 
     aes(x=Model, y=mpg)) + 
    geom_bar(stat="identity") + 
    theme(axis.text.x=element_text(angle=-90, vjust=0.5, hjust=0)) 

enter image description here

+0

OK,這樣的作品,唯一的問題是我有30個變量,標籤都在彼此之上。我從另一個SO帖子中發現了這個:'ggplot(df.m,aes(value))+ geom_histogram(aes(fill = variable),position =「dodge」)'我怎樣才能將兩者結合起來? –

+0

查看更新的答案。 – eipi10

+0

是'ggplot(cbind(模型= rownames(mtcars),mtcars)[1:3,],...''不夠? – rawr

2

就試試這個:

df 
    sums 
a 122 
b 23 
c 321 

library(ggplot2) 
ggplot(df, aes(x=rownames(df), sums)) + geom_bar(stat='identity') 

enter image description here