[英]Cannot plot the barplot of the data in R
ggplot2
是tidyverse
软件包系列的一部分, tidyr
和dplyr
我也在下面的示例中使用。
%>%
(管道)运算符从dplyr
导入,并将一个 function 的 output 传递给另一个函数的第一个参数。 简而言之, x %>% f(y)
等价于f(x,y)
。
如果没有可重复的示例,我不能保证这会起作用,但我会告诉你通过它,以便你了解步骤。
require(ggplot2)
require(dplyr)
require(tidyr)
### Format the data ------------------------------------------------------
formattedData <-
myData %>%
select(product_title, max_rating, min_rating) %>% #select only the columns we need
## Pivot longer takes us from this:
# |product_name | min_rating | max_rating|
# |"foo" | 1 | 325 |
# to this:
# |product_name | name | value |
# |"foo" |"min_rating"| 1 |
# |"foo" |"max_rating"| 325 |
# That's the data format ggplot() needs to do its stuff
pivot_longer(cols = all_of(c("max_rating", "min_rating")))
### Plot the data -------------------------------------------------------
ggplot(formattedData, # The data is our new 'formattedData' object
# aesthetics - X axis is product_title, y axis is value, # bar colour is name
aes(x = product_title, y = value, fill = name)) +
geom_bar(stat = "identity", position = "dodge") + # using the values, rather than counting elements
scale_fill_manual(values = c("max_rating" = "orange", "min_rating" = "blue") + # custom colours
ggtitle("Top products ratings") +
ylab("Ratings")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.