简体   繁体   中英

Lines and legend in ggplot2

Having this two dataframes:

df1 <- structure(list(Year = structure(1:10, .Label = c("2011", "2012", 
"2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020"
), class = "factor"), Frequency = c(19L, 17L, 34L, 41L, 64L, 
81L, 97L, 116L, 136L, 63L)), class = "data.frame", row.names = c(NA, 
-10L))

df2 <- structure(list(Year = structure(1:10, .Label = c("2011", "2012", 
"2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020"
), class = "factor"), Frequency = c(46L, 36L, 73L, 73L, 116L, 
173L, 197L, 241L, 265L, 85L)), class = "data.frame", row.names = c(NA, 
-10L))

Using the two dataframe it is possible to plot the frequency with this commands

plot(df1$Year,df1$Frequency,
     ylim=range(c(df1$Frequency,df2$Frequency)),
     xlim=range(c(df1$Year,df2$Year)), type="b",col="red",
     xlab = "Year", ylab = "Frq",
     main="Frq from activity")

lines(df2$Year,df2$Frequency,col="blue", type="b")

# Add a legend
legend("topright", bty="n", legend=c("frq_df1", "frq_df2"),
       col=c("red", "blue"), lty=1, cex=0.8, pch = 1)

How is it possible to make it have the line of red as line?

perfect for a ggplot solution using the tidyverse

library(tidyverse)
df1 %>% 
  mutate(gr="frq_df1") %>% 
  bind_rows(mutate(df2, gr="frq_df2")) %>% 
ggplot(aes(Year, Frequency, color =gr, group  =gr)) + 
   geom_point() + 
   geom_line()

在此处输入图像描述

Using your code you have to transform the factor Year into a numeric in the plot function:

plot(as.numeric(df1$Year),df1$Frequency,
     ylim=range(c(df1$Frequency,df2$Frequency)),
     xlim=range(c(df1$Year,df2$Year)), type="b",col="red",
    xlab = "Year", ylab = "Frq",
    main="Frq from activity")

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM