简体   繁体   English

不能 plot R 中数据的条形图

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

I am new to R language and am performing analysis of a certain dataset.我是 R 语言的新手,正在对某个数据集进行分析。

Below is a dataframe that I have.下面是我拥有的 dataframe。

数据框

I want to plot something like this in R (Given below bar graph).我想在 R 中像这样的 plot (在条形图下方给出)。 I know how to do it in python but being a beginner in R I have no idea how to do so.我知道如何在 python 中做到这一点,但作为 R 的初学者,我不知道该怎么做。 Thanks in advance!提前致谢!

想要的结果

One solution is to use the ggplot2 package一种解决方案是使用 ggplot2 package

ggplot2 is part of the tidyverse family of packages, as are tidyr and dplyr which I also use in the example below. ggplot2tidyverse软件包系列的一部分, tidyrdplyr我也在下面的示例中使用。

The %>% (pipe) operator is imported from dplyr , and passes the output of one function into another function's first argument. %>% (管道)运算符从dplyr导入,并将一个 function 的 output 传递给另一个函数的第一个参数。 In a nutshell, x %>% f(y) is equivalent to f(x,y) .简而言之, x %>% f(y)等价于f(x,y)

I can't guarantee this will work without a reproducible example, but I'll talk you through it so you get the steps.如果没有可重复的示例,我不能保证这会起作用,但我会告诉你通过它,以便你了解步骤。

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