设置R中条形图的范围并显示项目数

时间:2017-11-06 07:49:19

标签: r ggplot2 plotly ggvis ggplotly

我使用以下命令从iris数据集创建了一个数据框:

new_iris = data.frame(iris$Species,iris$Sepal.Length)
range(iris$Sepal.Length)

第二个命令告诉我Sepal.Length的范围。我想使用plotly或ggplot2实现条形图,以便代码自动决定Sepal.Length的范围,然后每个范围包含一个条形,它给出该范围内所有Sepal.Length值的计数。所以,让我们说如果确定的范围是" 2-4"," 4-6"," 6-8",我应该得到3个酒吧这让我计算了#34; 2-4"," 4-6"之间的所有sepal.length值。和" 6-8"。也可以附加快照,在下面的图中,我希望编辑x轴标签,其中包含代码决定的范围和y轴标签" total_bill"与"案例"。谢谢,请帮助。

Snapshot for reference

1 个答案:

答案 0 :(得分:3)

iris$sepal_gp <- cut(iris$Sepal.Length, breaks=3, include.lowest=TRUE)
ggplot(iris, aes(sepal_gp, fill=Species)) + geom_bar()

enter image description here

编辑:

ggplot(iris, aes(sepal_gp, fill=sepal_gp)) + geom_bar()

enter image description here

删除图例并在ggplotly中输入自定义悬停文字:

(i)计算每组的计数

library(dplyr)
iris <- iris %>% 
     group_by(sepal_gp) %>% 
     mutate(sepal_gp_count = n())

(ii)在ggplot中插入自定义悬停文本:

 p <- ggplot(iris, aes(sepal_gp, fill=sepal_gp, text=paste("Case: <br>", sepal_gp, "<br> Count: <br>", sepal_gp_count))) + 
      geom_bar() 

(iii)用ggplotly绘图:

ggplotly(p, tooltip="text") %>%
     layout(showlegend=FALSE)