【问题标题】:Plot x variable as a factor while still retaining continuous placement on x-axis将 x 变量绘制为一个因子,同时仍保持在 x 轴上的连续放置
【发布时间】:2014-04-17 02:09:07
【问题描述】:

我有两个连续变量,我试图在 ggplot2 中相互绘制,但我想使用 geom_crossbar() 显示数据均值和标准误差。为了做到这一点,我需要将 x 轴绘制为一个因子,这很好,只是我无法在 x 轴上获得我想要的间距类型。有谁知道将 x 变量强制转换为连续变量的方法,即使它是离散的?

一些代码...

 # assemble data, calculate means and standard errors
 x <- c(rep(15, 10), rep(30, 10), rep(41, 10), rep(42, 10), rep(45, 10))
 y <- c(rnorm(10, 47, 15), rnorm(10, 35, 11), rnorm(10, 31, 12), rnorm(10, 37, 13), rnorm(10, 30, 10))

 dat <- data.frame(x,y)
 y.mean <- aggregate(dat$y, by=list(x=dat$x), mean)
 names(y.mean) <- c('x', 'mean')
 dat <- merge(dat, y.mean, by=c('x'))

 se <- function(x) sqrt(var(x) / length(x))
 y.se <- aggregate(dat$y, by=list(x=dat$x), se)
 names(y.se) <- c('x','se')
 dat <- merge(dat, y.se, by=c('x'))

 g <- ggplot(dat, aes(x=factor(x), y=mean, ymin= mean - se, ymax= mean + se))
 g + geom_crossbar(width=0.5) + geom_jitter(mapping=aes(x=factor(x), y=y), position=position_jitter(width=0.2))

如您所见,x 变量被放置为一个离散变量,就像它应该的那样。我实际上并不想要那个;相反,我希望将其视为连续变量。但是,我必须将 x 作为保持横杆的因素,否则横杆开始对我产生影响。我只会使用 geom_boxplot(),但我想要标准错误而不是四分位间距。

感谢您的帮助, 保罗

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    不知道你的数据很难知道,但听起来这里有一些不稳定的可视化问题......无论如何,我认为如果你有不同的数据源,这将更加简单 - 一个用于您的观点,一个用于您的观点对于盒子。在不解决任何其他问题的情况下,我将按照以下方式修改您的方法:

    dat <- data.frame(x,y)
    y.mean <- aggregate(dat$y, by=list(x=dat$x), mean)
    names(y.mean) <- c('x', 'mean')
    
    se <- function(x) sqrt(var(x) / length(x))
    y.se <- aggregate(dat$y, by=list(x=dat$x), se)
    names(y.se) <- c('x','se')
    dat.mean <- merge(y.mean, y.se, by=c('x'))
    
    library(ggplot2)
    g <- ggplot(dat, aes(x, y)) + geom_point()
    g + geom_crossbar(data = dat.mean, aes(y = mean, 
      ymin = mean - se, ymax = mean + se, group = x))
    

    如果您希望 x 轴标签反映您的“水平”(x 是一个因素吗?我认为这是一个需要解决的重要问题),您可以添加:

    scale_x_continuous(breaks = dat.mean$x)
    

    【讨论】:

    • 上图正是我想要的。谢谢,alexwhan!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 2022-01-13
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多