Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在ggplot2中收缩图形时,将标签保持在固定距离_R_Ggplot2 - Fatal编程技术网

R 在ggplot2中收缩图形时,将标签保持在固定距离

R 在ggplot2中收缩图形时,将标签保持在固定距离,r,ggplot2,R,Ggplot2,我将调查数据可视化,并比较黑人和白人学生的回答。我创建了一个函数来创建哑铃图 dumbbell = function(df) { ggplot(df, aes(pct_responses, Domain)) + geom_line(aes(group=Domain)) + geom_point(aes(color=race), size=5) + vertical_theme + #custom theme that I made scale_color_ma

我将调查数据可视化,并比较黑人和白人学生的回答。我创建了一个函数来创建哑铃图

dumbbell = function(df) {
  ggplot(df, aes(pct_responses, Domain)) +
    geom_line(aes(group=Domain)) +
    geom_point(aes(color=race), size=5) +
    vertical_theme + #custom theme that I made
    scale_color_manual(labels = c("Black Students", "White Students"), 
                       values=c("#073b47", "#e59918")) +
    scale_x_continuous(expand = c(0, 0), 
                       limits=c(0,100), 
                       breaks = seq(0, 100, by=20),
                       labels = function(x) paste0(x,"%")) +
    labs(x = "% of Affirmative Responses") +
    scale_y_discrete(labels = wrap_format(40)) +
    geom_text_repel(aes(label=paste0(round(pct_responses),"%")), size=3.52778, family="Georgia", nudge_y=0.3, nudge_x=1.6, segment.color=NA)
}
即使我输入了“微移”(nudge_y)以使标签与彩色圆圈保持固定距离,但当我将图形保存为不同大小时,标签和圆圈之间的空间会发生变化。参见下面的示例:

dumbbell(df)
ggsave("test1.png", w=6.5, h=3, unit="in")
ggsave("test2.png", w=6.5, h=3.6, unit="in")


如何保持固定距离?

轻推y=0.3
将标签移动0.3个单位(其中每个y标签之间的隐式距离为1个单位)。但是,当使用更大的物理尺寸渲染打印时,沿轴0.3个单位的物理距离将更大。您可以尝试将微移量计算为绘图渲染高度的一部分,但使用
vjust
可能更容易,这将使标签保持在哑铃附近。以下是一个示例(数据改编自):


是否可以为“微移y”或“微移x”指定不同的单位,例如点/像素/英寸?好的,您只能以轴单位为“微移”*指定距离。
library(tidyverse)

health <- read.csv("https://raw.githubusercontent.com/selva86/datasets/master/health.csv")
health$Area <- factor(health$Area, levels=as.character(health$Area))

dat = health %>% 
  slice(1:3) %>% 
  gather(key, value, -Area)

ggplot(dat, aes(value, Area)) +
  geom_line(aes(group=Area)) +
  geom_point(aes(color=key), size=5) +
  geom_text(aes(label=paste0(round(value*100),"%")), size=3.52778, 
            family="Georgia", vjust=-1.5) +
  scale_y_discrete(expand=c(0.2,0)) +
  theme_classic()

ggsave("test1.png", w=6.5, h=3, unit="in")
ggsave("test2.png", w=6.5, h=4, unit="in")
ggplot(dat, aes(value, Area)) +
  geom_line(aes(group=Area)) +
  geom_point(aes(color=key), size=9) +
  geom_text(aes(label=paste0(round(value*100, 1),"%")), size=3.5, 
            family="Georgia", colour="white") +
  theme_classic()