简体   繁体   English

ggplot2 中的线条和图例

[英]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使用两个 dataframe 可以使用此命令 plot 频率

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非常适合使用tidyverse的 ggplot 解决方案

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:使用您的代码,您必须将因子Year转换为 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")

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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