使用ggplot2将组平均线添加到barplot

时间:2018-06-15 20:34:28

标签: r ggplot2 bar-chart

我生成一个带有geom_col()的条形图,其中两个类用颜色分隔。然后我尝试为每个班级添加一条平均线。

这是我想要的:

Desired output

但是使用下面的代码,每个柱的平均线是独立于我对组参数的放置。

这是一个可重复的例子:

library(tidyverse)

df = data.frame(
  x = 1:10,
  y = runif(10),
  class = sample(c("a","b"),10, replace=T) %>% factor()
) %>% 
  mutate(x = factor(x, levels=x[order(class, -y)]))

ggplot(df, aes(x, y, fill=class)) +
geom_col() +
stat_summary(fun.y = mean, geom = "errorbar", 
             aes(ymax = ..y.., ymin = ..y.., group = class),
             width = 1, linetype = "solid")

What I get

请告诉我我做错了什么。或者用其他任何方式(用ggplot)来实现这个目标?

4 个答案:

答案 0 :(得分:2)

创建一个新的geom_segment(添加组均值)并对其进行一些操作(使用# add group mean df_m <- df %>% group_by(class) %>% mutate(my = mean(y)) %>% arrange(class) # added from comment by @Yuk # select top and bottom x for each class group # use cbind to keep one row per group df_m2 <- df_m %>% top_n(1, x) %>% cbind(top_n(df_m, -1, x)) ggplot(df) + geom_col(aes(x, y, fill=class))+ geom_segment(data = df_m2, aes(x = x, xend = x1, y = my, yend = my1, group = class)) java.sql.SQLException: Failed to start database 'school' with class loader sun.misc.Launcher$AppClassLoader@b4aac2, see the next exception for details. ),然后使用它们为{{1}提供必要的美学效果}}:

package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {
    private static final String USERNAME = "rss";
    private static final String PASSWORD = "westerly";


    public static Connection getConnection(String driver, String database) 
    throws SQLException{
        String URL;
        switch (driver) {
            case "mysql":
                URL ="jdbc:" + driver + "://localhost:3306/" + database + "? 
                      useSSL=false";
                System.out.println(URL);
                return DriverManager.getConnection(URL, USERNAME, PASSWORD);
            case "derby":

                URL = "jdbc:derby:" + database ;
                System.out.println(URL);
                return DriverManager.getConnection(URL);

            default:
                System.out.println("only use mysql or derby");
                System.exit(0);
                return null;                
        }
    }

This is the closest I've found

答案 1 :(得分:2)

我使用@geom_errorbar将@bouncyball的解决方案与我的原始方法结合在一起。

代码如下:

df.mean = df %>% 
  group_by(class) %>% 
  mutate(ymean = mean(y))

ggplot(df, aes(x, y, fill=class)) +
  geom_col() +
  geom_errorbar(data=df.mean, aes(x, ymax = ymean, ymin = ymean),
               size=0.5, linetype = "longdash", inherit.aes = F, width = 1)

enter image description here

唯一的问题是,这种方法不是生成单线,而是生成许多线对象,这些对象可以在编辑绘图时看到,例如在Adobe Illustrator中。但是我可以忍受。

答案 2 :(得分:2)

使用现有的 ggplot ,请尝试以下代码:

+
geom_hline(data = [*name of data frame*], aes(yintercept = mean(*name of the variable*), color = "red")

答案 3 :(得分:0)

我将其添加为答案,因为@Ryan给出的先前答案似乎是部分答案,并且不包含@yuk请求的整个代码块。

如果df2是您的数据框,其中包含以下代码中使用的sitespCount_site列:

library (ggplot2)
p <- ggplot(data = df2, aes(x = site, y = spCount_site)) +
  geom_bar(stat = "identity", fill = rainbow(nrow(df2))) +
  geom_hline(yintercept = mean(df2$spCount_site), color="black") # a horizontal line of black color will be drawn at a height using the mean of `spCount_site` column
p

下面的图片是我根据自己的数据使用上面的代码创建的

enter image description here