簡體   English   中英

如何使用不同的顏色來表示 R 中的幾列分類二進制數據?

[英]How to use different color to represent several column of categorical binary data in R?

我有一個數據集,它以寬格式表示銀行信用系統的貸方特征。 我想使用 ggplot 制作散點圖,其中顏色代表信用的目的。 我的表看起來像這樣:其中 1 表示信用的目的。

貸款期限 貸款金額 家具 電視/收音機 房子
1個月 2000年 0 1 0 0
16個月 15600 1 0 0 0
4個月 13094 0 0 0 1
等等...

我試過: ggplot(Data, aes(x = DURATION, y = AMOUNT))+ geom_point(aes(color = c(Car, Furniture, 'TV/Ratio', House))+ scale_color_viridis_c()不工作。另一個問題是如何轉義變量名中的 / ,例如這里的 TV/(OR)Radio,我嘗試使用 '' 來轉義變量中的 / 但似乎不起作用。有人可以在這里幫助我嗎?非常感謝!

這是兩個問題的解決方案。 您可以通過簡單地將它們放在反引號中來重命名包含特殊字符的列:

library(tidyverse)
library(RColorBrewer)

# your sample data in a df
df <- tibble(lending_duration = c("1 month", "16 month", "4 month"), 
       lending_amount = c(2000, 15600, 13094), 
       Car = c(0, 1 ,0), 
       furniture = c(1,0,0), 
       `TV/Radio` = c(0, 0, 0),
       House = c(0, 0, 1)) 

df %>%  rename(TV_or_Radio = `TV/Radio`) %>% 
  pivot_longer(cols = c(Car, furniture, TV_or_Radio, House)) %>% 
  filter(value != 0) %>%
  # split string in lending_duration and use only first part converted to numeric, 
  # allows to plot durations in increasing order
  mutate(lending_duration = as.numeric(str_split(lending_duration, " ") %>% map_chr(., 1))) %>% 
  ggplot(aes(lending_duration, lending_amount, color = name)) +
  geom_point(size = 3) +
  scale_color_viridis_d() +
  xlab("lending_duration in month")

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM