我有这个数据框:
`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
并使用以下代码创建一个分组条形图:
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))
我还创建了一个新数据框,用于保存每个特征中 3 个姓氏的平均值:
mean_name means
1 Action 4.000000
2 Reflection 4.000000
3 Flexibility 3.666667
4 Structure 3.666667
我设法只绘制了线条,但未绘制在条形图中,请帮忙!
答案 0 :(得分:0)
假设您的代码正确,可以将 geom_line()
添加到您的情节中,除非您在整个情节中将 group
美学设置为相同(例如 aes(group=1)
)。这是因为您的 x 轴由离散值组成,而 ggplot
不知道它们通过一条线与您的数据相连。当您在美学中设置 group=1
时,它会强制 ggplot2
识别整个数据集是绑定在一起的,然后您的线的点将被连接。
我会使用您分享的数据进行展示,但它提供的图表与您展示的不同,因此这是一个具有代表性的示例。
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)
下面的代码不会在图上创建一条线(你也不会得到错误,它只是不会出现):
p + geom_line(data=d_myline, aes(x=x, y=rando))
但是,如果您设置 group=1
,它会按预期显示该行:
p + geom_line(data=d_myline, aes(x=x, y=rando, group=1))