0

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.

1
  • 1
    Nice advice from AndrewGB. Also see the R equisse package: rdocumentation.org/packages/esquisse/versions/1.1.0 It is a very nice drag and drop ggplot builder for R. You can build out an advanced plot and then copy and paste the code that is generated into R studio to fine tune. There are some tutorial vids on YouTube. Commented May 6, 2022 at 20:40

1 Answer 1

3

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.