简体   繁体   English

如何使用 ggplot2 使用轴标签和旋转在 R 中格式化雷达图

[英]How to format a radar chart in R with axis labels and rotation using ggplot2

I have a radar chart in r that shows percentages by month.我在 r 中有一个雷达图,按月显示百分比。 I would like to我想要

  • change the chart so that Jan starts at 90% angle rather than rotated to the right更改图表,让 Jan 从 90% 的角度开始,而不是向右旋转
  • change the chart so that the labels for the percentages show up in the chart rather than on the left side更改图表,使百分比标签显示在图表中而不是左侧

The bad chart is below坏图如下

辐射坏

The good chart I would like to replicate is below我想复制的好图表如下

在此处输入图片说明

The code for the radar chart is below雷达图的代码如下

library(reshape2)
library(ggplot2)
library(dplyr)

Group <- factor(c("Jan", "Feb", "Mar", "Apr", "May", "Jun",
                  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"),
                levels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun",
                           "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
Urban <- c(-0.61, 0.13, 0.24, -0.30, -0.12, -1.24, 0.74, 0.55, 0.80, .2, .2, .2)
Rural <- c(1.02, -0.40, 0.73, 0.17, 0.68, 1.21, -1.35, -0.84, -1.27, .2, .2, .2)
Total <- c(0.41, -0.27, 0.97, -0.13, 0.56, -0.03, -0.61, -0.29, -0.47, 0.4, 0.4, 0.4)

# data preparation
df = data.frame(Group = Group,
                Urban = Urban,
                Rural = Rural,
                Total = Total)    
df.m <- melt(df, 
             id.vars = c("Group"), 
             measure.vars = c("Urban", "Rural","Total"),
             variable.name = "Demographics",
             value.name = "Percentage")

# plot
ggplot(data = df.m,
       aes(x = Group, y = Percentage, group = Demographics, colour = Demographics)) + 
  geom_polygon(size = 1, alpha= 0.2) + 
  ylim(-2.0, 2.0) + ggtitle("Radar")  + 
  scale_x_discrete() +
  theme_light() +
  scale_color_manual(values = c("Red", "Blue","Black")) +
  scale_fill_manual(values = c("Red", "Blue","Black")) +
  coord_polar()

I don't know a way with normal scale_y_continuous terms to get the y-axis scale to appear in the plot rather than on its edges, but it can be faked using annotate to create an ad hoc layer.我不知道使用正常 scale_y_continuous 项的方法来使 y 轴比例出现在图中而不是其边缘,但可以使用annotate伪造它以创建临时图层。 We can also rotate the polar transformation with the start term in coord_polar .我们还可以使用coord_polarstart项旋转极坐标变换。

ggplot(data=df.m,  aes(x=Group, y=Percentage, group= Demographics, colour=Demographics )) + 
  annotate("text", x = 1, y = -2:2, label = -2:2, hjust = 1) +
  geom_polygon(size = 1, alpha= 0.2) + 
  ggtitle("Radar")  + 
  scale_y_continuous(labels = NULL) +
  scale_x_discrete() +
  scale_color_manual(values= c("Red", "Blue","Black"))+
  scale_fill_manual(values= c("Red", "Blue","Black"))+
  theme_light()+
  coord_polar(start = -pi/12)

在此处输入图片说明

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

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