ggplot2 geom_line R

I am trying to plot two line graphs for two different years of dataframe. However, I am getting error:

geom_path: Each group consists of only one observation. Do you need to adjust the group
aesthetic?

Could you please advise how to solve it? Thanks

library(tidyverse)

# example data
df2<-data.frame(c(1000,700),c(2000,1500))
rownames(df2)<-c("Revenue", "EBITDA")
colnames(df2)<-c("2020", "2021")

# reshape dataset
df2_upd = df2 %>% rownames_to_column("Financials") %>% gather(year, value, -Financials) 

print(df2_upd)

# plot using the new dataset

ggplot(data=df2_upd, aes(x=year, y=value, fill=Financials)) + geom_line()

You need to use the group parameter in the aesthetic to tell geom_line which points belong together. Also, a line's color is controlled with color not with fill.

library(ggplot2)
library(tibble)
library(tidyr)

df2<-data.frame(c(1000,700),c(2000,1500))
rownames(df2)<-c("Revenue", "EBITDA")
colnames(df2)<-c("2020", "2021")

# reshape dataset
df2_upd = df2 %>% rownames_to_column("Financials") %>% gather(year, value, -Financials) 

print(df2_upd)
#>   Financials year value
#> 1    Revenue 2020  1000
#> 2     EBITDA 2020   700
#> 3    Revenue 2021  2000
#> 4     EBITDA 2021  1500

# plot using the new dataset

ggplot(data=df2_upd, aes(x=year, y=value, color=Financials, group = Financials)) + geom_line()

Created on 2019-03-21 by the reprex package (v0.2.1)

1 Like

The year column in the data frame is not numeric. Using as.numeric()

ggplot(data=df2_upd, aes(x=as.numeric(year), y=value, colour=Financials)) + geom_line()

will work without group parameter.

Alternatively one can use gather(..., convert = TRUE) to auto-convert numeric columns.

This topic was automatically closed 21 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.