【问题标题】:Plotting a bar chart with smoothing line using ggplot in R在 R 中使用 ggplot 绘制带有平滑线的条形图
【发布时间】:2020-08-10 16:40:15
【问题描述】:

我在 R 中工作。我已经基于两个向量构建了一个数据框。这用于创建带有平滑线(plot1)的散点图。这没有问题。但我也需要一个带有平滑线的条形图。绘图已绘制,但没有平滑线 (plot2)。

library(ggplot2)

# Fill two vectors month and sale
month_short <- substr(month.name,1,3)
month <- factor(month_short, levels=month_short)
sales <- c(3189.0, 3063.0, 1084.6, 3151.80, 352.0, 5915.55, 2619.9, 493.0, 758.5, 45.0, 1704.0, 2608.0)

# Build dataframe
df <- data.frame(month, sales)
df

# Scatter chart with ggplot
plot <- ggplot(data=df, aes(x=month, y=sales, group=1)) + 
  labs(title="Sales to UK in 2015",x = "Month", y = "Sales (EUR)") +
  geom_line() +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) 
plot

# Bar chart with ggplot
plot2 <- ggplot(data=df, aes(x=month, y=sales)) + 
  labs(title="Sales to UK in 2015",x="Month", y = "Sales (EUR)") +
  geom_col() +
  geom_smooth(method = "lm", se = FALSE)
plot2

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您将需要aes(group=1) 选项,就像第一个情节一样。可以专门添加到geom_smooth层

    ggplot(data=df, aes(x=month, y=sales)) + 
      labs(title="Sales to UK in 2015",x="Month", y = "Sales (EUR)") +
      geom_col() + 
      geom_smooth(aes(group=1), method = "lm", se = FALSE)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      相关资源
      最近更新 更多