[英]Plot line on ggplot2 grouped bar chart
I have this data frame:我有这个数据框:
`Last Name` Feature Value
<chr> <chr> <dbl>
1 Name1 Resilience 1
2 Name2 Resilience 6
3 Name3 Resilience 2
4 Name1 Self-Discipline 3
5 Name2 Self-Discipline 7
6 Name3 Self-Discipline 4
7 Name1 Assertiveness 6
8 Name2 Assertiveness 7
9 Name3 Assertiveness 6
10 Name1 Activity level 4
and created a grouped barplot with the following code:并使用以下代码创建了一个分组条形图:
bar2 <- ggplot(team_sih_PP1, aes(x=Feature, y=Value, fill =`Last Name`)) + geom_bar(stat="identity", position="dodge") + coord_cartesian(ylim=c(1,7)) + scale_y_continuous(n.breaks = 7) +scale_fill_manual(values = c("#2a2b63", "#28d5ac", "#f2eff2")) + theme_bw() + theme(axis.text.x = element_text(angle = 90, hjust = 1))
I also created a new data frame that holds the average values of the 3 Last Names in each Feature:我还创建了一个新的数据框,其中包含每个特征中 3 个姓氏的平均值:
mean_name means
1 Action 4.000000
2 Reflection 4.000000
3 Flexibility 3.666667
4 Structure 3.666667
I want to add a line that shows the means of each Feature so that it looks something like this:我想添加一行来显示每个功能的方式,使其看起来像这样:
I managed to plot just the line but not in the bar chart, please help!我设法 plot 只是线但不在条形图中,请帮忙!
Assuming you have your code correct for geom_line()
to add to your plot, you will not see anything plotted unless you set the group
aesthetic the same across your plot (ex. aes(group=1)
).假设您将
geom_line()
的代码正确添加到 plot 中,除非您在 plot (例如aes(group=1)
)中设置相同的group
美学,否则您将看不到任何绘制的内容。 This is because your x axis is made of discrete values, and ggplot
does not know that they are connected with your data via a line.这是因为您的 x 轴由离散值组成,而
ggplot
不知道它们通过一条线与您的数据相连。 When you set group=1
in the aesthetic, it forces ggplot2
to recognize that the entire dataset is tied together, and then the points of your line will be connected.当您在美学中设置
group=1
时,它会强制ggplot2
识别整个数据集是捆绑在一起的,然后您的线的点将被连接起来。
I'd show using your data you shared, but it does not provide the same plots as you've shown, so here's a representative example.我会使用您共享的数据来展示,但它没有提供与您展示的相同的图,所以这是一个有代表性的例子。
x_values <- c('These', 'Values', "are", "ordered", "but", "discrete")
set.seed(8675309)
df <- data.frame(
x=rep(x_values, 2),
type=rep(c("A", "B"), each =6),
y=sample(1:10, 12, replace=TRUE)
)
df$x <- factor(df$x, levels=x_values)
d_myline <- data.frame(
x=x_values,
rando=c(1,5,6,10,4,6)
)
p <- ggplot(df, aes(x,y)) +
geom_col(aes(fill=type), position="dodge", width=0.5)
The following code will not create a line on the plot (you won't get an error either, it just won't appear):以下代码不会在 plot 上创建一行(您也不会收到错误,只是不会出现):
p + geom_line(data=d_myline, aes(x=x, y=rando))
However, if you set group=1
, it shows the line as expected:但是,如果您设置
group=1
,它将按预期显示该行:
p + geom_line(data=d_myline, aes(x=x, y=rando, group=1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.