I have created a data frame from iris dataset using the following command:
new_iris = data.frame(iris$Species,iris$Sepal.Length)
range(iris$Sepal.Length)
The second command tells me the range of the Sepal.Length. I want to implement a bar plot using plotly or ggplot2 such that the code decides the ranges of Sepal.Length automatically and then each range contains one bar which gives the count of all the Sepal.Length values in that range. So let's say if the ranges decided are "2-4","4-6","6-8", I should get 3 bars which give me a count of all the sepal.length values between "2-4","4-6" and "6-8". Attaching the snapshot too, In the plot below, I wish to edit x-axis labels with the ranges that the code will decide and y-axis label "total_bill" with "cases". Thanks and please help.
iris$sepal_gp <- cut(iris$Sepal.Length, breaks=3, include.lowest=TRUE)
ggplot(iris, aes(sepal_gp, fill=Species)) + geom_bar()
Edit:
ggplot(iris, aes(sepal_gp, fill=sepal_gp)) + geom_bar()
To remove legend and put in custom hover text in ggplotly:
(i) calculate the count for each group
library(dplyr)
iris <- iris %>%
group_by(sepal_gp) %>%
mutate(sepal_gp_count = n())
(ii) insert custom hover text in 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) plot with ggplotly:
ggplotly(p, tooltip="text") %>%
layout(showlegend=FALSE)
来源:https://stackoverflow.com/questions/47132076/setting-ranges-for-a-bar-chart-in-r-and-displaying-count-of-items