【问题标题】:Change color of plot in R更改 R 中绘图的颜色
【发布时间】:2020-05-28 13:44:09
【问题描述】:

我正在尝试找出我无法更改条形颜色的原因。希望你能帮忙,我对此有点陌生。

ggplot2(data, aes(x = data$Crop, y = data$"2018"))+
    geom_bar(color="black", fill="red") +
    theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1)) +
    main="Production value per crop in 2018" +
    ylab("Production value in 2018")+
    xlab("Crop")+

希望收到您的来信。

【问题讨论】:

  • 请分享reproducible example。至少有一些数据,这样我们就可以自己运行代码了。
  • ggplot(data, aes(x=Crop)) + geom_bar(color="black", fill="red") 应该可以解决问题。您的预期输出和实际输出是什么样的?
  • 您不应该在aes() 中使用$。最好切换到aes(x = Crop, y = `2018`)
  • 最终我成功了。

标签: r ggplot2 colors


【解决方案1】:

对您的代码稍作调整:

library(tidyverse)
data <- data.frame(Crop = c("East","West","North","South"),
                   Y2018 = c(1000,2000,3000,400),
                      stringsAsFactors = TRUE)

ggplot(data, aes(x = data$Crop, y = data$Y2018)) + 
  geom_col(color="black", fill="red") + 
  theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1)) + 
  labs(
    title = "Production value per crop in 2018",
    ylab = "Production value in 2018",
    xlab = "Crop"
  )

希望对你有帮助

【讨论】:

    【解决方案2】:

    这是有效的代码,尽管 xlab 给出了一个关于意外符号的错误

    setwd("C:/Users/####/OneDrive/Documenten") # include the path to your data
    data<-read_xlsx("datasetR.xlsx")
    str(data) # get an overview of the data
    
    
    library(ggplot2)
    library(tidyverse)
    dCrop <- data$Crop
    d2018 <- data$"2018"
    
    ggplot(data, aes(x = dCrop, y = d2018)) +
        geom_col(width=1, fill = "red") +
        theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1)) +
        ggtitle("Production value per crop in 2018")+
        ylab("Production value in 2018") +
        xlab("Crop")
    

    enter image description here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      相关资源
      最近更新 更多