根据其密度(频率)绘制颜色的圆圈

时间:2019-05-16 15:07:23

标签: r plot density-plot

我扔了一个球,并且每次都记录了我和球之间的距离。

最后,我可以根据距我的球距离绘制密度图。 但是,我想画一个圆,其半径为最大投射距离。此外,我想使用颜色渐变来表示不同频率的球数区域(如密度图)。 我如何用R做到这一点? (或其他方法?)

2 个答案:

答案 0 :(得分:2)

您可以将geom_segmentcoord_polar一起使用(为此,您必须自己预先计算密度)。

library(ggplot2)
# Lets calculate frequency of how far is the ball
d <- density(chickwts$weight)
# Here x is weight (or distance for OP) and y is frequency
pd <- data.frame(distance = d$x, frequency = d$y)

ggplot(pd, aes(x = 1, xend = 2, y = distance, yend = distance, color = frequency)) +
  geom_segment(stat = "identity") +
  coord_polar() +
  scale_color_viridis_c() +
  labs(
    title = "How far is the ball",
    x = "Distance",
    y = "Distance",
    color = "Frequency"
  ) +
  theme_classic() +
  theme(axis.text.x = element_blank())

enter image description here

如果需要分类分组,可以使用此分组:

# Check if frequency is within wanted range
pd$color <- pd$frequency > 0.002 & pd$frequency < 0.003    
ggplot(
  pd,
  aes(x = 1, xend = 2, y = distance, yend = distance, color = color)
) +
  geom_segment(stat = "identity") +
  coord_polar() +
  scale_color_viridis_d() +
  labs(
    title = "How far is the ball",
    x = "Distance",
    y = "Distance",
    color = "Frequency"
  ) +
  theme_classic() +
  theme(axis.text.x = element_blank())

答案 1 :(得分:0)

使用 mtcars 作为示例数据,绘制密度,然后转换为极坐标:

library(ggplot2)

ggplot(mtcars, aes(mpg)) +
  geom_density() +
  coord_polar()

enter image description here