首页 > 解决方案 > 将散点转换为单平均线图

问题描述

我有一个用下面的代码绘制的散点图。但我想画出每个行业的平均值。将 geom_point 转换为 geom_line 不会给出单条线,而是会给出类似图形的密度。

  output$ind=renderPlot({
     ggplot(data = dailyprice_gather[dailyprice_gather$Industry == input$industry2,]) +
     geom_point(aes(x= Date , y= cumulative, color=Industry) , size=0.25) +
     ggtitle(paste0("Simple Cumulative Return over Years - Industry Wise"))

     })

我的数据集样本是:

structure(list(Date = structure(c(17833, 17830, 17829, 17828, 
NA), class = "Date"), stocks = structure(c(1L, 1L, 1L, 1L, 1L
), .Label = c("DBS SP Equity", "OCBC SP Equity", "ST SP Equity"
), class = "factor"), cumulative = c(22.99, 23.1, 23.71, 24.1, 
NA), Industry = structure(c(1L, 1L, 1L, 1L, 1L), .Label = c("Banks", 
"Telecommunications"), class = "factor")), row.names = c(NA, 
-5L), class = c("tbl_df", "tbl", "data.frame"))

这是当前的 geom_point

我想绘制 1 条平均线而不是现在显示的 3 条。所以基本上绘制平均值(银行行业中的 3 只股票。其他行业可能有或多或少的股票数量

标签: rshiny

解决方案


这是你要找的吗?因为您的数据集不完整,所以我使用了该iris数据集。我首先计算您要显示的内容的平均值,并将其作为额外的列添加到数据框中。那么这个专栏在ggplot.

library(tidyverse)

data(iris)

iris <- iris %>% 
  group_by(Species) %>% 
  # calculate the mean of what your plotting on the y-axis
  mutate(Petal.Width.mean  = mean(Petal.Width))

iris %>% 
  ggplot(aes(x = Petal.Length, 
             y = Petal.Width, 
             color = Species)) +
  geom_point() +
  geom_line(aes(x = Petal.Length,
                y = Petal.Width.mean))

推荐阅读