Add points to the a stacked line graph?

I am trying to create a stacked line graph and I cannot add the points to the graph. Basically, I have a data.frame with 3 columns, Year, Delhi, LA. The rows represent the years for the Year column, and the HDI value for the other two columns.

When I create a stacked line graph, the result is:
Rplot

I would like to add points in the graph based on the row value (the points should have the same colour as the line graph. For example, the points for the bottom graph should have the same colour as the bottom graph. The same for the top graph).

I tried to add + geom_point(position=position_stack()) (among other things) but it gives me an error

Error in geom_point():
! Problem while setting up geom.
:information_source: Error occurred in the 3rd layer.
Caused by error in compute_geom_1():
! geom_point() requires the following missing aesthetics: y
Run rlang::last_trace() to see where the error occurred.

Here is the dataset:

structure(list(Year = 2015:2020, Delhi = c(0.734, 0.739, 0.743, 
0.744, 0.744, 0.74), LA = c(0.929, 0.932, 0.934, 0.937, 0.939, 
0.929)), class = "data.frame", row.names = c(NA, -6L))

The code:

library(ggplot2)
library(dplyr)

line_data <- read.csv("path/hdi.csv")

# define colours
Purple <- "#ff7c43"
Orange <- "#003f5c"

line_data %>% 
  ggplot(aes(x = Year)) +
  geom_line(aes(y = Delhi, colour = Purple)) +
  geom_line(aes(y = LA, colour = Orange)) + 
  theme_bw() + 
  theme(panel.border = element_blank(), 
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(), 
        axis.line = element_line(colour = "dark grey")) + 
  theme(legend.position = "none") + 
  labs(y = "HDI") + 
  theme(axis.text.x = element_text(colour="black")) + 
  theme(axis.text.y = element_text(colour="black")) + 
  scale_y_continuous(n.breaks = 16)+
  geom_point(position=position_stack())

I think the easiest approach is to reshape your data to have a column for the city identity and use that to set the colors.

line_data <- structure(list(Year = 2015:2020, Delhi = c(0.734, 0.739, 0.743, 
                                                        0.744, 0.744, 0.74), 
                            LA = c(0.929, 0.932, 0.934, 0.937, 0.939, 
                                   0.929)), class = "data.frame", row.names = c(NA, -6L))
library(ggplot2)
library(tidyr)
line_data_long <- line_data |> pivot_longer(cols = c("Delhi", "LA"),
                                            names_to = "City", 
                                            values_to = "Value")

Purple <- "#ff7c43"
Orange <- "#003f5c"

ggplot(line_data_long, aes(x = Year, y = Value, color = City)) +
  geom_line() + geom_point() +
  scale_color_manual(values = c(Delhi = Purple, LA = Orange))

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.