0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【R】メモ: 積み上げグラフの凡例の順番を指定する

Last updated at Posted at 2021-08-10

Rのggplot2による積み上げグラフ(棒グラフや面グラフ)において凡例順序を指定したいときのメモです。
今回は事例としてWorldPhonesのデータセットを取り扱いました。

library(tidyverse)

df <- data.frame(WorldPhones) %>% 
  rownames_to_column("year") %>% 
  gather(key="Country", value="Users", -year) %>% 
  mutate(year = as.integer(year))

# 凡例の順番を調整する前
g1 <-
  ggplot(df, aes(x=year, y=Users, fill=Country)) + 
  geom_area() +
  scale_fill_brewer("blues")
g1.png

これを例えばAsia, Europe, Mid.Amer, Oceania, S.Amer, Africa, N.Amer
の順番で表示させたい時はこう書けば出来ます。

fill_order <- c('Asia', 'Europe', 'Mid.Amer',
                'Oceania', 'S.Amer', 'Africa', 'N.Amer')

g2 <-
  ggplot(df, aes(x=year, y=Users, fill=factor(Country, fill_order))) + 
  geom_area() +
  scale_fill_brewer("blues")
g2.png
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?