【问题标题】:How can I show only the top 10 categories and values in geom_point dot plot?如何在 geom_point 点图中仅显示前 10 个类别和值?
【发布时间】:2019-07-24 04:16:46
【问题描述】:

我想用点图排列订购次数最多的产品,按降序显示它们的订购时间。但是有 134 个产品,所以点图被压扁了。所以我需要整理出情节中前10的产品,我如何编辑代码?

这是我的绘图数据:

head(product_count)

product                    order_times
frozen juice                    2
baby bath body care             7
Indian foods                    7
beauty                          8
bulk grains rice dried goods    8

代码:

library(scales)
theme_set(theme_classic())

ggplot(product_count,aes(x=product, y=order_times)) + 
   geom_point(col="tomato2", size=1) +   
   geom_segment(aes(x=product, 
               xend=product, 
               y=min(order_times),
               yend=max(order_times)), 
               linetype="dashed", 
               size=0.1) +  
labs(title="Dot Plot", 
     subtitle="Product Vs Order times") +  
coord_flip()

实际点图有 134 行,但我只想显示 10 行(前 10 行)

【问题讨论】:

  • 类似df %>% top_n(10) %>% ggplot() + aes(product, order_times) + geom_point() ?
  • product_count %>% top_n(10) %>% ggplot() 中的错误:找不到函数“%>%”
  • 如果尚未安装,您需要执行library(dplyr)install.packages("dplyr")
  • 啊哈成功了。非常棘手。

标签: r sorting ggplot2


【解决方案1】:

您可以使用 top_n 过滤前 10 个值,然后使用它在 ggplot 对象中绘图

library(dplyr)
library(ggplot2)

df %>% 
  top_n(10, order_times) %>% 
  ggplot() + aes(product, order_times) + geom_point() 

或者只使用ggplot2

ggplot(df[tail(order(df$order_times), 10), ], ) + 
     aes(product, order_times) + geom_point() 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 2015-03-06
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    相关资源
    最近更新 更多