在重新排序x后,请填写ggplot2

时间:2017-09-02 19:12:57

标签: r ggplot2

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

现在我希望fill值与x轴上的值具有相同的顺序。我用order尝试了它,但它不起作用。

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

2 个答案:

答案 0 :(得分:1)

按照您的方式行事,您可以按照以下示例:

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

或者我认为更好的解决方案是创建一个有序的因子,它也会命令填充:

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

答案 1 :(得分:0)

希望这会让你朝着正确的方向前进。一旦您对基本图表感到满意,就可以开始调整主题(例如主题(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()