简体   繁体   中英

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:

    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!

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) ). 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. 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.

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):

p + geom_line(data=d_myline, aes(x=x, y=rando))

However, if you set group=1 , it shows the line as expected:

p + geom_line(data=d_myline, aes(x=x, y=rando, group=1))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM