I'm trying to use R for plotting a combo chart like the one in the image.
I tried to use the code displayed in the tutorial linked below, which used the line representation for the dot, but it gives me the errorr "geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
(https://www.geeksforgeeks.org/combine-bar-and-line-chart-in-ggplot2-in-r/).
Do you have any suggestion on how to do it?
I tried to use the code below, I don't know if the variable in the first column of the csv file is accepted for the x axis as it's composed by country names.
library(readr)
ComboR <- read_csv("C:/Users/Giulio/Downloads/ComboR.csv")
View(ComboR)
library(ggplot2)
dataco <- data.frame(ComboR$...1, ComboR$B2014, ComboR$`BAU 2050`)
ggp <- ggplot(dataco) +
geom_bar(aes(x=ComboR$...1, y=ComboR$B2014),stat="identity", fill="cyan",colour="#006000")+
geom_line(aes(x=ComboR$...1, y=ComboR$`BAU 2050`),stat="identity",color="red",size=2)+
labs(title= "try",
x="commodities",y="%import")
ggp
The problem is that your x-axis is categorical while that of the example is continuous. You need to put a group = 1
option in your aesthetics to tell ggplot that you are considering the full data, and not just the data by location. So for your code to work, you should have something like
Location <- c("Rest Western EU", "Netherlands", "China Region", "Eastern
EU", "Former Soviet Union")
B2014 <- c(0.24, 0.23, 0.09, 0.05, 0.05)
BAU2050 <- c(0.22, 0.24, 0.09, 0.04, 0.04)
dataco <- data.frame(Location, B2014 , BAU2050)
ggp <- ggplot(dataco) +
geom_bar(aes(x=Location, y=B2014),stat="identity", fill="cyan",colour="#006000")+
geom_line(aes(x=Location, y=BAU2050, group = 1),stat="identity",color="red",size=2)+
labs(title= "try",
x="commodities",y="%import") +
scale_y_continuous(sec.axis=sec_axis(~.*1,name="Percentage"))
ggp
ggplot geom_bar: meaning of aes(group = 1) discusses the use of group = 1
.
You wouldn't need a line graph here since your location is categorical. So instead, you should use geom_point
instead of geom_line
and you do not have to use group = 1
anymore.
ggp <- ggplot(dataco) +
geom_bar(aes(x=Location, y=B2014),stat="identity", fill="cyan",colour="#006000")+
geom_point(aes(x=Location, y=BAU2050),stat="identity",color="red",size=2)+
labs(title= "try",
x="commodities",y="%import") +
scale_y_continuous(sec.axis=sec_axis(~.*1,name="Percentage"))
ggp
But since the scales of your B2014
and BAU2050
are the same, why don't you instead use just one y axis like the one below.
dataco |>
pivot_longer(cols = c("B2014", "BAU2050"),
names_to = "Source",
values_to="Percent") %>%
ggplot(aes(x = Location, y = Percent, fill = Source)) +
geom_bar(stat = "identity", position = "dodge")