【问题标题】:Changing color of density plots in ggplot2 based on x axis基于x轴改变ggplot2中密度图的颜色
【发布时间】:2016-04-15 17:03:24
【问题描述】:

我有一些想要可视化的数据,我可以在左侧制作图表,但我希望能够通过实现右侧图像中的功能向查看者提供更多信息:根据预定义的范围和每个范围内的面积百分比进行着色。

我认识到这个问题与这两个答案相似,但是我对密度的了解不足以以正确的格式获取数据帧:

这是复制我的示例的代码。

如果可以,请在回复中使用 dplyr。

提前谢谢你。

library(dplyr)
library(ggplot2)
options(scipen = 999)

#Get percentages
  diamonds%>%
    mutate(Cut = cut,
           Prices = cut(price, 
                        breaks=c(0,2499,4999, 19000), 
                        include.lowest=T, dig.lab=10))%>%
    group_by(Cut, Prices)%>%
      summarise(Count = n())%>%
    group_by(Cut)%>%
      mutate(Pct = round(Count/sum(Count), 2))%>%
    ungroup()


#Plot
  ggplot(diamonds, aes(x=price))+
    geom_density(fill="grey50")+
    facet_grid(cut~.)+
    geom_vline(xintercept = c(2500,5000))+
    theme(axis.text.y = element_blank(),
          axis.ticks.y = element_blank())

【问题讨论】:

  • 您通过处理步骤传输的diamonds 数据与ggplot 调用之间没有任何联系。

标签: r ggplot2 dplyr


【解决方案1】:

问题是diamondsdata.frame 中没有密度数据。您面临的另一个问题是您需要保留方面信息。我不确定如何让dplyrcut 分组并获得density()。可以像您一样生成摘要数据,但为了制作密度图,您需要每个点的 x,y 信息。

我发现的一种解决方法是像这样制作密度图 p

p<-ggplot(diamonds,aes(x=price))+geom_density()+facet_wrap(~cut,nrow=5)

然后使用 ggplot_build 函数获取正在绘制的数据

pg <- ggplot_build(p)

这会得到一个列表,其中第一个元素是实际的数据集

pg_data<-data.frame(pg$data[[1]],stringsAsFactors = F)

您可以检查您是否对 y 列(与密度相同)感兴趣,x 将是价格,而 PANEL 将是方面。我没有将其更改为 Good、Very Good... 的因子模式,但我猜你可以。

head(pg_data)
              y        x       density    scaled      count    n PANEL group
1 0.00005370272 326.0000 0.00005370272 0.2756038 0.08646139 1610     1    -1
2 0.00005829975 362.1977 0.00005829975 0.2991959 0.09386259 1610     1    -1
3 0.00006307436 398.3953 0.00006307436 0.3236993 0.10154972 1610     1    -1
4 0.00006798165 434.5930 0.00006798165 0.3488836 0.10945045 1610     1    -1
5 0.00007298816 470.7906 0.00007298816 0.3745772 0.11751094 1610     1    -1
6 0.00007807049 506.9883 0.00007807049 0.4006598 0.12569348 1610     1    -1
  ymin          ymax fill weight colour alpha size linetype
1    0 0.00005370272   NA      1  black    NA  0.5        1
2    0 0.00005829975   NA      1  black    NA  0.5        1
3    0 0.00006307436   NA      1  black    NA  0.5        1
4    0 0.00006798165   NA      1  black    NA  0.5        1
5    0 0.00007298816   NA      1  black    NA  0.5        1
6    0 0.00007807049   NA      1  black    NA  0.5        1

现在我们可以再次绘制所有内容,但使用我们需要的密度数据

ggplot(data=pg_data,aes(x,y))+geom_line()+facet_wrap(~PANEL,nrow=5)+geom_area(data=subset(pg_data,x>2499&x<5000),aes(x,y),fill = "red", alpha = 0.5)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 2013-01-07
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 2014-03-26
    • 2018-05-27
    • 1970-01-01
    相关资源
    最近更新 更多