0
0

More than 1 year has passed since last update.

ggplotで凡例の形を色ごとに変えたい(R-wakalangへの質問と回答)

Last updated at Posted at 2023-02-04

Question

R-wakalangにこんな質問をした。

ggplotを用いて、次のような図を描きました。
penguinsの種族と性別ごとの違いに注目するために、
species列とsex列を合わせたspecies_sex列を作り、
bill_length_mmとbody_mass_gで散布図を作っています。
区別のため、species_sex列で色分けし、sex列ごとに点のshapeを変えています。
ここで、凡例のspecies_sexの説明で、sexごとにshapeを変える(Maleを▲、Femaleを●に合わせる)にす>るようなことはできるでしょうか。

Question.R
library(palmerpenguins)
library(tidyverse)

short_penguins <-  penguins %>%
  filter(!is.na(sex)) %>%
  sample_n(30,replace=FALSE) %>%
  transform(species_sex = paste(species,sex,sep="-"))
  
ggplot(short_penguins, aes(x=bill_length_mm,
                           y=body_mass_g,
                           color=species_sex,
                           shape=sex)) +
  geom_point() 
  

要するに、ここの形を変えたい。
penguin_sex.png

Answer

( Thanks to tasasaki様)
このあたりが参考になりそうです
https://stackoverflow.com/questions/12410908/combine-legends-for-color-and-shape-into-a-single-legend

scale_color_manual、scale_shape_manualを使うといいようです。

Answer1.R
short_penguins <-  penguins %>%
  filter(!is.na(sex)) %>%
  sample_n(30,replace=FALSE) %>%
  transform(species_sex = paste(species,sex,sep="-"))
  
ggplot(short_penguins, aes(x=bill_length_mm,
                           y=body_mass_g,
                           color=species_sex,
                           shape=species_sex)) + #colorとsphapeでおなじものを指定
  geom_point() +
  scale_color_manual(values=c("red","red","blue","blue","green","green")) +
  scale_shape_manual(values=c("circle","triangle","circle","triangle","circle","triangle"))

Qiita-penguins2.png

色を変える必要がない場合には、scale_shape_manualだけでも大丈夫

Anser2.R
short_penguins <-  penguins %>%
  filter(!is.na(sex)) %>%
  sample_n(30,replace=FALSE) %>%
  transform(species_sex = paste(species,sex,sep="-"))
  
ggplot(short_penguins, aes(x=bill_length_mm,
                           y=body_mass_g,
                           color=species_sex,
                           shape=species_sex)) + #colorとsphapeでおなじものを指定
  geom_point() +
 scale_shape_manual(values=c("circle","triangle","circle","triangle","circle","triangle")) +
  labs(color = "Species and sex", shape = "Species and sex") #ラベルを変えるときは、ShapeとColorを同じ名前にする

Qiita-penguins3.png

さいごに

r−wakalangのr-beginnersチャンネルでは、R初心者のちょっとした疑問を、Rつよつよなお兄さん、お姉さんたちが爆速で解説してくれます。(いつも大変お世話になっております)
みなさんとってもフレンドリーなので、みんなで楽しくRを勉強しましょう!
(腕に覚えのある皆様はご回答のほうも何卒)

参考:

0
0
1

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