使用 ggplot (R) 用字符串标记轴时遇到问题

trouble with labeling axis with strings using ggplot (R)

我是一名大学生,我们必须使用 Rstudio 创建一些图表来完成一项作业。我已经完成了第一个任务的核心 objective,即使用提供的数据创建一个简单的条形图;但是,我在用所需文本标记坐标轴时遇到了问题。

代码如下:

library (ggplot2)

Country = as.factor(c("slovakia", "iceland", "lithuania"))
Waste = c(2.0, 3.7, 2.1, 2.3, 1.7, 2.5)
Year = as.factor(c("2004", "2018"))

data = data.frame(Country, Waste, Year)

ggplot(data,                                    
       aes(x = Country,
           y = Waste,
           fill = Year)) +
  geom_bar(stat = "identity",
           position = "dodge") 
 xlab("Country")
   ylab("Tons of waste per capita")

这是输出:

但我希望轴标签具有此特定文本(用 Word 制作):

请注意,我们被特别要求使用 ggplot

使用 ggplot2,您必须在代码行的末尾使用 + 才能为绘图添加额外的图层。如果不是,那么 R 只是将这些代码行作为独立行读取,这将引发错误。因此,在您的代码中,geom_barxlab 末尾缺少符号,这意味着 x 和 y 标签线永远不会添加到您的绘图中。

library(ggplot2)

ggplot(data,                                    
       aes(x = Country,
           y = Waste,
           fill = Year)) +
  geom_bar(stat = "identity",
           position = "dodge") +
xlab("Country") +
ylab("Tons of waste per capita")

输出

数据

data <- structure(list(Country = structure(c(3L, 1L, 2L, 3L, 1L, 2L), class = "factor", levels = c("iceland", 
"lithuania", "slovakia")), Waste = c(2, 3.7, 2.1, 2.3, 1.7, 2.5
), Year = structure(c(1L, 2L, 1L, 2L, 1L, 2L), class = "factor", levels = c("2004", 
"2018"))), class = "data.frame", row.names = c(NA, -6L))