r - geom_point 在 geom_极地饼图(圆环图)图表的开头引入偏移

标签 r plot ggplot2 pie-chart

在使用 ggplot2 创建饼图时,我偶然发现了极坐标图开始时的奇怪行为。如果我们采用

dta <- data.frame(val = 1:60, col = rep(c(0,1), each = 10))

并使用

制作饼图
library(ggplot2)
ggplot(dta, aes(x = val, y = 2, fill = factor(col), color = factor(col))) + 
  geom_col() + 
  coord_polar(start = 0)

我们最终得到了预期的饼图: enter image description here

假设我们想在图表中间创建一个小圆环孔,我们可以通过在中间添加一个点来实现:

ggplot(dta, aes(x = val, y = 2, fill = factor(col), color = factor(col))) + 
  geom_col() + 
  coord_polar(start = 0) + 
  geom_point(aes(0,0), size = 30, color = "lightgrey", show.legend = FALSE) 

但是,这一点引入了饼图开头的奇怪变化,导致顶部出现一个小的灰色扇区。

enter image description here

为什么会造成这种转变?如何避免呢?顺便提一句。这种转变也由其他几何对象引入,例如geom_vline(xintercept = 0)

最佳答案

该转变看起来像是来自 ?scale_x_continuous()。它的 expand 参数表示:“连续变量的默认值为 c(0.05, 0),离散变量的默认值为 c(0, 0.6)。”。

因此,如果您想消除这种差距,您可以在 aes() 之外定义 geom_point() 层,以防止 scale_x_continuous 得到涉及那里:

ggplot(dta, aes(x = val, y = 2, fill = factor(col), color = factor(col))) + 
    geom_col() + 
    coord_polar(start = 0) +
    geom_point(x = 0, y = 0, size = 30, color = "lightgrey", show.legend = FALSE)

enter image description here

或者调整传递给 expand 参数的值:

ggplot(dta, aes(x = val, y = 2, fill = factor(col), color = factor(col))) + 
    geom_col() + 
    coord_polar(start = 0) + 
    geom_point(aes(0,0), size = 15, color = "lightgrey", show.legend = FALSE) +
    scale_x_continuous(expand = c(0,-.25))

我不确定为什么 c(0,0) 没有产生所需的输出...

enter image description here

对于 geom_vline() 情况(再次不确定为什么会这样,coord_polar() 是个挑剔的家伙),我们可以添加 geom_vline(xintercept = .5 ),采用上述任一策略,并获得适当放置的垂直线:

ggplot(dta, aes(x = val, y = 2, fill = factor(col), color = factor(col))) + 
    geom_col() + 
    coord_polar(start = 0) +
    geom_point(x = 0, y = 0, size = 30, color = "lightgrey", show.legend = FALSE) +
    geom_vline(xintercept = .5)

enter image description here

我认为第一个策略更好,因为第二个策略似乎使颜色边界(和 vline)明显倾斜远离“真正的”垂直方向。第一次在小预览窗口中没有看到这一点。

关于r - geom_point 在 geom_极地饼图(圆环图)图表的开头引入偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46878709/

相关文章:

R 中指定列数上矩阵的 rowsum

r - 不循环查找

还原列表结构

R flexdashboard仪表功能不会改变颜色

r - 使用 R 中的 ggplot 将数据分组为多个季节和箱线图?

r - 使用 sf、ggplot 和 cut_interval() 的 Choropleth 中的组数错误

渐变颜色的matlab contourf

python - 在 python 中绘制填充的多边形

r - 如何使用 ggplot2 绘制矩阵并为相同的值保持相同的颜色

r - 如何在这个由几个不同的几何图形组成的ggplot中手动指定图例文本/颜色?