使用ggplot coord_pol()时如何在面板外添加文本?

问题描述 投票:0回答:1

我想创建一个图作为连续变量的圆形图例。此外,我需要在面板外部添加文本,特别是在 x 轴下方(圆圈之外)。但是,由于我使用的是

coord_polar()
,因此
annotate()
geom_text()
等函数的行为不会像平常那样。有人对如何解决这个问题有建议吗?

数据如下:

# DATA
aspect_class = data.frame(from = c(0, seq(22.5, 337.5, by = 45)),
                          to =   c(seq(22.5, 337.5, by = 45), 360),
                          mid = seq(0, 360, by = 45),
                          class = c("North (0°-22.5°)", 
                                    "Northeast (22.5°-67.5°)",
                                    "East (67.5° - 112.5°)",
                                    "Southeast (112.5°-157.5°)",
                                    "South (157.5°-202.5°)",
                                    "Southwest (202.5°-247.5°)",
                                    "West (247.5°-292.5°)",
                                    "Northwest (292.5°-337.5°)",
                                    "North (337.5°-360°)"))

degrees = seq(0, 360, by = 1)
values = sin(degrees * pi / 180)
aspect_legend_df = data.frame(degrees, values)
compas = data.frame(degrees = seq(0,315,45),
                    direction = c("N", "NE", "E", "SE", "S", "SW", "W", "NW"))

和情节代码:

# PLOT
ggplot() +
  geom_tile(data = aspect_legend_df, 
            aes(x = degrees, y = 0, fill = values), 
            width = 1, height = 0.1) +
  scale_x_continuous(breaks = compas$degrees, 
                     labels = ~ paste0(.x, "\u00B0"),
                     name = "Aspect [°]") +
  scale_fill_viridis_c() +
  geom_vline(data = aspect_class[aspect_class$mid %in% c(0, 90, 180, 270),],
             aes(xintercept = mid), 
             color = "black", linewidth = 0.8) +
  geom_vline(data = aspect_class[!aspect_class$mid %in% c(0, 90, 180, 270, 360),],
             aes(xintercept = mid), 
             color = "black", linewidth = 0.5, linetype = "dotdash") +
  annotate(geom = "text", x = compas$degrees, y = 0.06, label = "") +    
  coord_polar(start = 0) + 
  theme_minimal() +
  theme(legend.position = "none",
        axis.title = element_blank(),
        axis.text.y = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.text.x = element_text(size = 12, color = "black")) 

我想要这个:

plot

如果我使用

annotate(geom = "text", x = compas$degrees, y = 0.06, label = compas$direction) +
我得到:

plot w annotate

如果我使用

geom_text(data = compas,aes(x = degrees, y = 0.06, label = direction), inherit.aes = FALSE, size = 5)
我得到:

plot w geom_text

r ggplot2 text panel
1个回答
0
投票

您可以通过用空格和换行符标记中断来做到这一点。例如,如果您有:

  scale_x_continuous(breaks = compas$degrees, 
                     labels = c("N\n0°", "45°", "90° E", "135°", "180°\nS",
                                "225°", "W 270°", "315°"),
                     name = "Aspect [°]") 

你得到了

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.