我有一个真实用例的精简版本,我创建了一个甜甜圈图,并希望这些长标签适合整个情节,但在甜甜圈之外:
library(ggplot2)
df <- data.frame(group = c("Cars", "Trucks", "Motorbikes"),n = c(25, 25, 50),
label2=c("Cars are blah blah blah", "Trucks some of the best in town", "Motorbikes are great if you ..."))
df$ymax = cumsum(df$n)
df$ymin = cumsum(df$n)-df$n
df$ypos = df$ymin+df$n/2
df$hjust = c(0,0,1)
df
#> df
# group n label2 ymax ymin ypos hjust
#1 Cars 25 Cars are blah blah blah 25 0 12.5 0
#2 Trucks 25 Trucks some of the best in town 50 25 37.5 0
#3 Motorbikes 50 Motorbikes are great if you ... 100 50 75.0 1
bp <- ggplot(df, aes(x="", y=n, fill=group)) + geom_rect(aes_string(ymax="ymax", ymin="ymin", xmax="2.5", xmin="2.0")) +
theme(axis.title=element_blank(),axis.text=element_blank(),panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid=element_blank(),axis.ticks.length=unit(0,"cm"),axis.ticks.margin=unit(0,"cm"),
legend.position="none",panel.spacing=unit(0,"lines"),plot.margin=unit(c(0,0,0,0),"lines"),complete=TRUE) + geom_text(ggplot2::aes_string(label="label2",x="2.6",y="ypos",hjust="hjust"))
pie <- bp + coord_polar("y", start=0) + scale_x_discrete(labels=df$label2)
pie
但无论我做什么,这都是我得到的:
我尝试降低xmax="2.5"
以尝试减小甜甜圈图的大小并相应地更新自定义文本的x,例如+0.1 x="2.6"
。然而,这导致整个情节重新缩小到相同的情况。
我玩过不同的地块尺寸和边距,但找不到路......
答案 0 :(得分:2)
如果我理解正确,你希望相对于整个情节区域缩小甜甜圈,以便有更多空间来容纳长注释?我根据示例数据得到以下工作。您可能希望调整实际用例的参数:
library(dplyr); library(stringr)
ggplot(df %>%
mutate(label2 = str_wrap(label2, width = 10)), #change width to adjust width of annotations
aes(x="", y=n, fill=group)) +
geom_rect(aes_string(ymax="ymax", ymin="ymin", xmax="2.5", xmin="2.0")) +
expand_limits(x = c(2, 4)) + #change x-axis range limits here
# no change to theme
theme(axis.title=element_blank(),axis.text=element_blank(),
panel.background = element_rect(fill = "white", colour = "grey50"),
panel.grid=element_blank(),
axis.ticks.length=unit(0,"cm"),axis.ticks.margin=unit(0,"cm"),
legend.position="none",panel.spacing=unit(0,"lines"),
plot.margin=unit(c(0,0,0,0),"lines"),complete=TRUE) +
geom_text(aes_string(label="label2",x="3",y="ypos",hjust="hjust")) +
coord_polar("y", start=0) +
scale_x_discrete()