我用下面的代码绘制了一个散图图。但是我想对每个行业的平均值画一条线。将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"))
我想绘制1条平均线,而不是现在显示的3条线。所以基本上是绘制平均值(银行行业中有3只股票。其他行业中可能有或多或少的股票
答案 0 :(得分:1)
这是您要寻找的吗?因为您的数据集不完整,所以我使用了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))
答案 1 :(得分:0)
这有帮助吗?
+ geom_smooth(method = lm,se = FALSE)