繁体   English   中英

不能 plot R 中数据的条形图

[英]Cannot plot the barplot of the data in R

我是 R 语言的新手,正在对某个数据集进行分析。

下面是我拥有的 dataframe。

数据框

我想在 R 中像这样的 plot (在条形图下方给出)。 我知道如何在 python 中做到这一点,但作为 R 的初学者,我不知道该怎么做。 提前致谢!

想要的结果

一种解决方案是使用 ggplot2 package

ggplot2tidyverse软件包系列的一部分, tidyrdplyr我也在下面的示例中使用。

%>% (管道)运算符从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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM