r - 如何在 geom_point 点图中仅显示前 10 个类别和值?

标签 r sorting ggplot2

我想用点图排列订购最多的产品,按降序显示它们的订购时间。但由于产品有 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 行)

最佳答案

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

关于r - 如何在 geom_point 点图中仅显示前 10 个类别和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57175180/

相关文章:

java - Java中具有相同值但不同标识的元素的排序列表

swift - 按键排序词典

r - 通过gganimate和ggforce进行动态小平面缩放的动画图?

重命名多列并在 R 中使用 dplyr 进行收集

r - 将多个功能应用于数据框的每一行

r - 如何通过另一个矩阵的值过滤矩阵

r - 无法删除文件 - 打开我的 Rstudio

r - 是否有 R 函数根据最接近的给定值对数据帧进行排序?

r - ggplot2 箱线图的两种不同颜色/图案方案

r - 如何使用 plot_grid 自定义边距和标签设置?