首页 > 解决方案 > 根据密度(频率)画一个有颜色的圆

问题描述

我扔过一个球,我每次都记录下球和我之间的距离。我可以根据与我的球距离绘制密度图。但是,我想画一个圆,其半径为最大投掷距离。

此外,我想使用颜色渐变来表示具有不同球数频率的区域(作为密度图)。

我怎样才能用 R 实现这一点?

标签: rplotdensity-plot

解决方案


您可以使用geom_segmentwith coord_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())

在此处输入图像描述

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

# 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())


推荐阅读