-2

I reordered my values in ggplot2:

KR %>% ggplot(aes(x= reorder(categories, -n), n, fill = categories, order = 
categories)) + geom_bar(stat = "identity") + (axis.title.x=element_blank(), 
axis.text.x=element_blank(), axis.ticks.x=element_blank()) 

Now I want that the fill values have the same order as the values on the x-axis. I tried it with order but it doesn't work.

str(KR)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   20 obs. of  2 variables:
$ categories: chr  "Food" "Nightlife" "Bars" "American (Traditional)" ...
$ n         : int  8576 6334 6067 5312 5250 5229 5220 4118 3868 3673 ...

Picture of the plot

neilfws
  • 32,751
  • 5
  • 50
  • 63
Hadsga
  • 185
  • 2
  • 4
  • 15
  • Welcome to Stack Overflow. Please reconstruct your example in a reproducible way. Try using a built-in data set. Please see this for guidance: http://stackoverflow.com/help/mcve and https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Hack-R Sep 02 '17 at 19:16

2 Answers2

1

Doing it your way you can follow the below example:

library(tibble)
KR <- data_frame(
  categories=c("Food","Nightlife","Bars","American (Traditional)"),
  n=c(576,6334,6067,5312))
str(KR)
#Classes ‘tbl_df’, ‘tbl’ and 'data.frame':  4 obs. of  2 variables:
#$ categories: chr  "Food" "Nightlife" "Bars" "American (Traditional)"
#$ n         : num  576 6334 6067 5312

library(ggplot2)
KR %>% 
  ggplot(aes(x= reorder(categories, -n), y=n, fill = reorder(categories, -n), order = categories)) + 
  geom_bar(stat = "identity") + 
  theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) 

Or I think better solution is to create an ordered factor which will order also the fill:

KR$categories <- factor(KR$categories,
                        levels=c("Nightlife","Bars","American (Traditional)","Food"), 
                        ordered = T)
KR %>% 
  ggplot(aes(x= categories, y=n, fill = categories)) + 
  geom_bar(stat = "identity") + 
  theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) 

enter image description here

Patrik_P
  • 3,066
  • 3
  • 22
  • 39
0

Hopefully, this will get you going in the right direction. Once you are happy with the basic chart, you can start tweaking the theme (ex. theme(axis.title.x = element_blank() ...)

suppressPackageStartupMessages(library(tidyverse))

# generate example data frame
KR <- tibble(categories = rep(c("Food", "Nightlife", "Bars", "Other"), each = 3),
             x = ceiling(runif(12, min = 5000, max = 9000)))

# build chart
KR %>%
  count(categories, wt = x) %>% 
  mutate(categories = reorder(categories, -n)) %>% 
  ggplot(aes(x= categories, n, fill = categories)) + 
  geom_col()

LVG77
  • 196
  • 6