Kub*_*ba_ 6 visualization r ggplot2
我有一个与此类似的数据集:
x <- 100 - abs(rnorm(1e6, 0, 5))
y <- 50 + rnorm(1e6, 0, 3)
dist <- sqrt((x - 100)^2 + (y - 50)^2)
z <- exp(-(dist / 8)^2)
Run Code Online (Sandbox Code Playgroud)
可以看作如下:
data.frame(x, y, z) %>%
ggplot() + geom_point(aes(x, y, color = z))
Run Code Online (Sandbox Code Playgroud)
我想做的是一个堆叠的半圆图,后续图层的平均值为z.我认为它可以与组合来实现geom_col和coord_polar(),虽然我可以得到最远
data.frame(x, y, z, dist) %>%
mutate(dist_fct = cut(dist, seq(0, max(dist), by = 5))) %>%
ggplot() + geom_bar(aes(x = 1, y = 1, fill = dist_fct), stat = 'identity', position = 'fill') +
coord_polar()
Run Code Online (Sandbox Code Playgroud)
这显然远远超出预期(图层应该是相同的大小,图应该被剪裁在右半边).
问题是coord_polar()由于进一步使用我无法真正使用annotate_custom().所以我的问题是:
coord_polar()吗?coord_polar()呢?如果您想要简单的半径带,也许这样的东西可以像您在问题中所描绘的那样工作:
# your original sample data
x <- 100 - abs(rnorm(1e6, 0, 5))
y <- 50 + rnorm(1e6, 0, 3)
dist <- sqrt((x - 100)^2 + (y - 50)^2)
nbr_bands <- 6 # set nbr of bands to plot
# calculate width of bands
band_width <- max(dist)/(nbr_bands-1)
# dist div band_width yields an integer 0 to nbr bands
# as.factor makes it categorical, which is what you want for the plot
band = as.factor(dist %/% (band_width))
library(dplyr)
library(ggplot2)
data.frame(x, y, band) %>%
ggplot() + geom_point(aes(x, y, color = band)) + coord_fixed() +
theme_dark() # dark theme
Run Code Online (Sandbox Code Playgroud)
当您第一次尝试时,最好使用非常方便的cut()函数来计算半径颜色类别。
为绘图颜色组获取分类(离散)颜色而不是连续着色的一种方法是将 aes 设置color=为因子列。
要直接从您那里获取因素cut()可以使用选项ordered_result=TRUE:
band <- cut(dist, nbr_bands, ordered_result=TRUE, labels=1:nbr_bands) # also use `labels=` to specify your own labels
data.frame(x, y, band) %>%
ggplot() + geom_point(aes(x, y, color = band)) + coord_fixed()
Run Code Online (Sandbox Code Playgroud)
或者更简单地,您可以cut()不带选项地使用并使用以下方法转换为因子as.factor():
band <- as.factor( cut(dist, nbr_bands, labels=FALSE) )
data.frame(x, y, band) %>%
ggplot() + geom_point(aes(x, y, color = band)) + coord_fixed()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
255 次 |
| 最近记录: |