简体   繁体   English

ggplot2 中的点在 R 中没有被正确躲避

[英]Points in ggplot2 not being dodged correctly in R

I am trying to make these plots by dodging points.我试图通过躲避点来制作这些情节。 The points radius differ by size.点半径因大小而异。 Ideally, there have to be four points in each "coordinate" as indicated by the dataframe.理想情况下,每个“坐标”中必须有四个点,如数据框所示。 The didge does not seem to work for two of the points.对于其中的两个点,didge 似乎不起作用。 I tried changing the width to 5 but I can't see the points.我尝试将width更改为 5,但看不到点。 Any clue on what's going on?关于发生了什么的任何线索?

library(ggplot2)
set.seed(123)
species <- rep(c("A","B","C","D"), each = 5)
x.axis <- rep(c(0.5, 0.5, 1, 1,0.75), each = 4)
y.axis <- rep(c(0.5, 1, 1, 0.5,0.75), each = 4)
value <- c(1,2,10,3,4,5,4,3,2,3,6,5,10,4,5,17,1,10,13,3)
data <- data.frame(specie,value, x.axis, y.axis)


# 2D plots
ggplot(data, aes(x = x.axis, y = y.axis, color = value, size = value)) + 
theme_classic() + 
geom_point(aes(fill = species, color = species), alpha = 0.7,position = position_dodge(width = 0.05)) + 
theme(text=element_text(size=10,  family="Arial", color = "black")) + 
theme(aspect.ratio = 10/10) +  
theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.background = element_rect(colour = "black", size=1)) + 
theme(axis.title.y = element_text(margin = margin(t = 0, r = 0, b = 0, l = 0)))

在此处输入图像描述

Maybe this is what you are looking for.也许这就是你要找的。 The way your points get dodged is determined by the grouping.您的积分被躲避的方式由分组决定。 In your case the data by default gets grouped by the variable mapped on the color aes, ie species .在您的情况下,默认情况下数据由映射在color aes 上的变量分组,即species Hence, at each position or coordinate only points with different species get dodged.因此,在每个位置或坐标处,只有具有不同species的点才会被躲避。

As far as I understand your question you want to dodge all points at the same position or coordinate instead.据我了解您的问题,您想避开同一位置或坐标的所有点。 To this end you could add an id column to your dataset by position, ie as we have four points at each position the points are assigned an id running from 1 to 4. This id column could then be mapped on the group aesthetic:为此,您可以按位置向数据集添加一个id列,即,由于我们在每个位置有四个点,因此这些点被分配了一个从 1 到 4 的id 。然后可以将该id列映射到group美学上:

library(dplyr)
library(ggplot2)

data <- data |> 
  group_by(x.axis, y.axis) |> 
  mutate(id = row_number())

# 2D plots
ggplot(data, aes(x = x.axis, y = y.axis, size = value)) +
  theme_classic() +
  geom_point(aes(color = species, group = id), alpha = 0.7, position = position_dodge(width = 0.05)) +
  theme(text = element_text(size = 10, family = "Arial", color = "black")) +
  theme(aspect.ratio = 10 / 10) +
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_rect(colour = "black", size = 1)
  ) +
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 0, b = 0, l = 0)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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