【问题标题】:R - ggplot geom_dotplot shape optionR - ggplot geom_dotplot 形状选项
【发布时间】:2016-01-09 15:31:11
【问题描述】:

我想使用geom_dotplot 通过点的形状(而不是文档建议的颜色)来区分两个不同的变量。例如:

library(ggplot2)
set.seed(1)
x = rnorm(20)
y = rnorm(20)
df = data.frame(x,y)
ggplot(data = df) + 
   geom_dotplot(aes(x = x), fill = "red") + 
   geom_dotplot(aes(x=y), fill = "blue")

即区分下例中的 x 和 y

我想将所有 x 设置为点,将 y 设置为三角形。

这可能吗? 谢谢!

【问题讨论】:

标签: r ggplot2 data-visualization shape


【解决方案1】:

您可能会使用 geom_dotplot 中的信息加上 base R 的 stripchart 函数来拼凑类似于您想要的东西。

#Save the dot plot in an object.

dotplot <- ggplot(data = df) +
geom_dotplot(aes(x = x), fill = "red") +
geom_dotplot(aes(x=y), fill = "blue")

#Use ggplot_build to save information including the x values.
dotplot_ggbuild <- ggplot_build(dotplot)

main_info_from_ggbuild_x <- dotplot_ggbuild$data[[1]]
main_info_from_ggbuild_y <- dotplot_ggbuild$data[[2]]

#Include only the first occurrence of each x value.

main_info_from_ggbuild_x <- 
main_info_from_ggbuild_x[which(duplicated(main_info_from_ggbuild_x$x) == FALSE),]

main_info_from_ggbuild_y <-
main_info_from_ggbuild_y[which(duplicated(main_info_from_ggbuild_y$x) == FALSE),]

#To demonstrate, let's first roughly reproduce the original plot.

stripchart(rep(main_info_from_ggbuild_x$x,
times=main_info_from_ggbuild_x$count),
pch=19,cex=2,method="stack",at=0,col="red")      

stripchart(rep(main_info_from_ggbuild_y$x,
times=main_info_from_ggbuild_y$count),
pch=19,cex=2,method="stack",at=0,col="blue",add=TRUE)

#Now, redo using what we actually want.
#You didn't specify if you want the circles and triangles filled or not. 
#If you want them filled in, just change the pch values.

stripchart(rep(main_info_from_ggbuild_x$x,
times=main_info_from_ggbuild_x$count),
pch=21,cex=2,method="stack",at=0)

stripchart(rep(main_info_from_ggbuild_y$x,
times=main_info_from_ggbuild_y$count),
pch=24,cex=2,method="stack",at=0,add=TRUE)

【讨论】:

    猜你喜欢
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 2013-06-02
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多