简体   繁体   English

ggplot2:coord_polar()与geom_col()

[英]Ggplot2: coord_polar() with geom_col()

I have an issue when using coord_polar() together with geom_col() . coord_polar()geom_col()一起使用时出现问题。 I have degree values ranging from 0 to <360. 我的学位数值范围从0到<360。 Let's say there are in steps of 20, so 0, 20, 40... 340 . 假设有20步,所以0, 20, 40... 340 If I plot them with coord_polar() I have two issues: 如果我使用coord_polar()绘制它们, coord_polar()有两个问题:

  • values 0 and 340 touch each other and don't have the same gap as the other columns 值0和340彼此接触,并且与其他列的间距不同
  • the "x-axis" is offset slightly, so that 0 does not point "north" “ x轴”略有偏移,因此0不会指向“北”

See this minimal example. 请参阅此最小示例。



suppressWarnings(library(ggplot2))


df <- data.frame(x = seq(0,359,20),y = 1)

ninety = c(0,90,180,270)

p <- ggplot(df, aes(x,y)) +
  geom_col(colour = "black",fill = "grey") +
  geom_label(aes(label = x)) + 
  scale_x_continuous(breaks = ninety) +
  geom_vline(xintercept = ninety, colour = "red") +
  coord_polar()

p

If I set the x-axis limits, the rotation of the coordinate system is correct, but the column at 0 disappears due to lack of space. 如果设置x轴极限,则坐标系的旋转是正确的,但由于空间不足,位于0的列消失了。


p+scale_x_continuous(breaks = c(0,90,180,270),limits = c(0,360))
#> Scale for 'x' is already present. Adding another scale for 'x', which
#> will replace the existing scale.
#> Warning: Removed 1 rows containing missing values (geom_col).

Created on 2019-05-15 by the reprex package (v0.2.1) reprex软件包 (v0.2.1)创建于2019-05-15

Since the space occupied by each bar is 20 degrees, you can shift things by half of that in both scales and coordinates: 由于每个条形图占据的空间为20度,因此您可以在比例尺和坐标上将其偏移一半:

ggplot(df, aes(x,y)) +
  geom_col(colour = "black",fill = "grey") +
  geom_label(aes(label = x)) + 
  scale_x_continuous(breaks = ninety,
                     limits = c(-10, 350)) + # shift limits by 10 degrees
  geom_vline(xintercept = ninety, colour = "red") +
  coord_polar(start = -10/360*2*pi) # offset by 10 degrees (converted to radians)

情节

I got it closer to what you want, but it's a bit of a hack so I don't know if it's a great solution. 我更接近您想要的东西,但这有点麻烦,所以我不知道这是否是一个很好的解决方案。

Code: 码:

df <- data.frame(x = seq(0,359,20),y = 1)

ggplot(df, aes(x+10,y, hjust=1)) +
  geom_col(colour = "black",fill = "grey") +
  geom_label(aes(x=x+5,label = x)) + 
  scale_x_continuous(breaks = c(0,90,180,270),limits = c(0,360)) +
  coord_polar() 

Instead of plotting the geom_cols's at c(0,20,40,...) I'm now plotting them at c(10,30,50,...). 我现在不在c(0,20,40,...)绘制geom_cols了,而是在c(10,30,50,...)绘制它们。 I'm plotting the geom_labels at c(5, 15, 25,...). 我正在c(5、15、25,...)绘制geom_labels。

The label positioning at the bottom of the chart is still not perfect since 180deg is not South. 由于180deg不在南方,因此标签在图表底部的位置仍然不够理想。

I get this graph: 我得到这张图: 在此处输入图片说明

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

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