【问题标题】:Why i see a bar plot with geom_line of ggplot in R?为什么我在 R 中看到带有 ggplot 的 geom_line 的条形图?
【发布时间】:2020-12-14 02:25:41
【问题描述】:

我有以下data.frame,其中我有多个变量,我想使用ggplot 绘制。我了解如果使用Date 而不拆分为YearMonthDay 将获得line plot,但我想知道,如何使用Year 列可以让我获得line plot

library(tidyverse)
library(lubridate)

set.seed(123)
DF <- data.frame(Date = seq(as.Date("2011-01-01"), to = as.Date("2014-12-31"), by = "day"),
                  F = runif(1461,20,60), D = runif(1461,30,70)) %>% 
                  separate(Date, into = c("Year", "Month", "Day")) 

ggplot(DF, aes(x = Year))+
  geom_line(aes(y = F)) +
    geom_line(aes(y = D))

【问题讨论】:

  • 我尝试了x = as.numeric(Year)as.integer(Year)ggploting 但没有成功。

标签: r ggplot2 plot tidyverse lubridate


【解决方案1】:

Year 设为数字,然后为y 选择某种汇总函数(否则你会得到看起来像条形的垂直线)。

DF %>%
  mutate(across(Year, as.numeric)) %>%
  ggplot(aes(x = Year))+
  geom_line(stat = "summary", aes(y = F), fun = mean, color = 'red') +
  geom_line(stat = "summary", aes(y = D), fun = mean, color = 'blue')

请注意,您可以通过将 FD 旋转到它们自己的列来简化一点:

DF %>%
  mutate(across(Year, as.numeric)) %>%
  pivot_longer(c(F, D)) %>%
  ggplot(aes(x = Year, y = value, color = name))+
  geom_line(stat = "summary", fun = mean)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 2013-06-02
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多