Jiaxiang
Jiaxiang

Reputation: 883

How to plot an area figure for a category variable

Here are two reproducible minimal examples for my request.

  1. In the first one, the x variable is a factor variable, I find the function geom_area does not work, works like a geom_segment output.
  2. In the second one, I transfer the x variable from factor into interger, the function geom_area works but I find the axis.text.y labels are not what I want.

Anyone know fix it?

suppressMessages(library(tidyverse))
mtcars %>% 
    rownames_to_column('index1') %>% 
    mutate(index1 = index1 %>% as.factor) %>% 
    mutate(index2 = index1 %>% as.integer) -> df

df %>% 
    ggplot() +
    geom_area(aes(x = index1, y = mpg), color = 'black', fill = 'black') +
    coord_flip()

enter image description here

df %>% 
    ggplot() +
    geom_area(aes(x = index2, y = mpg), color = 'black', fill = 'black') +
    coord_flip()

enter image description here

Upvotes: 2

Views: 33

Answers (1)

Paweł Chabros
Paweł Chabros

Reputation: 2399

Check this solution:

library(tidyverse)
library(wrapr)

df %.>% 
  ggplot(data = .) +
  geom_area(aes(x = index2, y = mpg), color = 'black', fill = 'black') +
  coord_flip() +
  scale_x_continuous(
    breaks = .$index2,
    labels = .$index1
  )

Upvotes: 1

Related Questions