如何在R中创建一个类似散点图,如箱形图? [英] How do I create a categorical scatterplot in R like boxplots?
问题描述
有谁知道如何在 R
中创建散点图来创建也可以显示个人数据点/rel =nofollow noreferrer>
我尝试过使用boxplots,但他们没有以我想要的方式显示数据。这些柱形图可以生成的散点图显示数据更好。
任何建议,将不胜感激。
正如@smillig所提到的,您可以使用ggplot2来实现这一点。下面的代码重现了你非常好的情节 - 警告它非常棘手。首先加载ggplot2包并生成一些数据:
library(ggplot2)
dd = data.frame(values = runif(21),type = c(Control,Treated,Treated + A))
下一步更改默认主题:
theme_set(theme_bw())
现在我们构建该图。
-
构建一个基础对象 - 没有任何东西被绘制:
<$ p $
$g = ggplot(dd,aes(type,values))
-
盒子:计算盒子的结束位置。在这种情况下,我选择了平均值。如果您不想使用此框,只需省略此步骤。
g = g + stat_summary (fun.y = function(i)mean(i),
$
geom =bar,fill =white,color =black)
-
添加一些错误栏:计算上下限并调整栏宽:
<$ (i)平均(i)+ qt(0.975,长度(i))* sd(i)/长度(i) i),
fun.ymin = function(i)mean(i) - qt(0.975,length(i))* sd(i)/ length(i),
geom =errorbar,宽度= 0.2)
-
显示图
g
添加点:调整默认的抖动并根据类型更改标志符号:
g = g + geom_jitter(aes (pch = type),position = position_jitter(width = 0.1))
- 在上面的R代码中,我使用
stat_summary
来计算所需的值。您也可以创建单独的数据框架并使用geom_errorbar
和geom_bar
。 - 要使用base R,请查看我对此问题的答案。
Does anyone know how to create a scatterplot in R
to create plots like these in PRISM's graphpad:
I tried using boxplots but they don't display the data the way I want it. These column scatterplots that graphpad can generate show the data better for me.
Any suggestions would be appreciated.
As @smillig mentioned, you can achieve this using ggplot2. The code below reproduces the plot that you are after pretty well - warning it is quite tricky. First load the ggplot2 package and generate some data:
library(ggplot2)
dd = data.frame(values=runif(21), type = c("Control", "Treated", "Treated + A"))
Next change the default theme:
theme_set(theme_bw())
Now we build the plot.
Construct a base object - nothing is plotted:
g = ggplot(dd, aes(type, values))
Add on the points: adjust the default jitter and change glyph according to type:
g = g + geom_jitter(aes(pch=type), position=position_jitter(width=0.1))
Add on the "box": calculate where the box ends. In this case, I've chosen the average value. If you don't want the box, just omit this step.
g = g + stat_summary(fun.y = function(i) mean(i), geom="bar", fill="white", colour="black")
Add on some error bars: calculate the upper/lower bounds and adjust the bar width:
g = g + stat_summary( fun.ymax=function(i) mean(i) + qt(0.975, length(i))*sd(i)/length(i), fun.ymin=function(i) mean(i) - qt(0.975, length(i)) *sd(i)/length(i), geom="errorbar", width=0.2)
Display the plot
g
- In my R code above I used
stat_summary
to calculate the values needed on the fly. You could also create separate data frames and usegeom_errorbar
andgeom_bar
. - To use base R, have a look at my answer to this question.
这篇关于如何在R中创建一个类似散点图,如箱形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!