Home > Net >  trouble with labeling axis with strings using ggplot (R)
trouble with labeling axis with strings using ggplot (R)

Time:05-08

I'm a college student and we have to create some graphs using Rstudio for an assignment. I've managed to do the core objective for this first task, which is to create a simple bar graph with the provided data; however, I'm having trouble with labeling the axes with the desired text.

Here's the code:

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")

This is the output: enter image description here

But I want the axis labels to have this specific text (made with Word): enter image description here

Please note that we were specifically asked to use ggplot.

CodePudding user response:

With ggplot2, you have to use at the end of your line of code to add additional layers to your plot. If not, then R just reads those lines of code as standalone lines, which will throw an error. So, in your code, the sign is missing at the end of geom_bar and xlab, which means the x and y label lines are never added to your plot.

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")

Output

enter image description here

Data

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))
  • Related