frida guo
frida guo

Reputation: 61

How can I show only the top 10 categories and values in geom_point dot plot?

I want to arrange the most ordered products with a dot plot, showing their order times in descending order. But there are 134 products so the dot plot are squashed. So I need to sort out top 10 products in the plot, how I edit the code?

Here is my data for the plot:

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

code:

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

Actual dot plot has 134 rows, but I want to show only 10 rows (top 10)

Upvotes: 2

Views: 8461

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389155

You could use top_n to filter top 10 values and then use it to plot in ggplot object

library(dplyr)
library(ggplot2)

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

Or using only ggplot2

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

Upvotes: 3

Related Questions