r 你更喜欢哪种方法?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了r 你更喜欢哪种方法?相关的知识,希望对你有一定的参考价值。

library(tidyverse)
library(forcats)

# The original plot
## This has an ugly legend title, maybe we should remove it and modify the labels
ggplot(mtcars, aes(x = mpg, y = disp, col = as.factor(cyl))) +
  geom_point()

# Approach 1: Modify the plot

# Use ggplot to map each level of a factor (specified with 'breaks') to a new lablel
ggplot(mtcars, aes(x = mpg, y = disp, col = as.factor(cyl))) +
  geom_point() +
  scale_color_discrete(name = "",
                       breaks = c(4,6,8), labels = c('4 cylinders','6 cylinders','8 cylinders'))

# Approach 2: Modify the data frame

## Option a: Use sprintf to create a new string based on the old one
mtcars %>%
  mutate(cyl_str = sprintf('%d cylinders', cyl)) %>%
  ggplot(aes(x = mpg, y = disp, col = cyl_str)) +
  geom_point() +
  scale_color_discrete(name = "")

## Option b: Create a factor and explicitly specify the levels and labels
### Note: this will break if cyl is already a factor unless you force as.character first
mtcars %>%
  mutate(cyl_factor = factor(cyl,
                             levels = c(4,6,8),
                             labels = c('4 cylinders','6 cylinders','8 cylinders'))) %>%
  ggplot(aes(x = mpg, y = disp, col = cyl_factor)) +
  geom_point() +
  scale_color_discrete(name = "")

## Option c: Use dplyr's recode_factor to change labels
### Note: old values on the left, new ones on the right
mtcars %>%
  mutate(cyl_factor = as.factor(cyl),
         cyl_factor = recode_factor(cyl_factor,
                                    "4"="4 cylinders", "6"="6 cylinders", "8"="8 cylinders")) %>%
  ggplot(aes(x = mpg, y = disp, col = cyl_factor)) +
  geom_point() +
  scale_color_discrete(name = "")

## Option d: Use forcat's fct_recode to change labels
### Note: new values on the left, old ones on the right (opposite of above)
mtcars %>%
  mutate(cyl_factor = as.factor(cyl),
         cyl_factor = fct_recode(cyl_factor,
                                 "4 cylinders"="4", "6 cylinders"="6", "8 cylinders"="8")) %>%
  ggplot(aes(x = mpg, y = disp, col = cyl_factor)) +
  geom_point() +
  scale_color_discrete(name = "")

## Option e: Use plyr's revalue
### Note: like previous option, but you pass a named vector instead of a sequence of named arguments
mtcars %>%
  mutate(cyl_factor = as.factor(cyl),
         cyl_factor = plyr::revalue(cyl_factor,
                                    c("4"="4 cylinders", "6"="6 cylinders", "8"="8 cylinders"))) %>%
  ggplot(aes(x = mpg, y = disp, col = cyl_factor)) +
  geom_point() +
  scale_color_discrete(name = "")

以上是关于r 你更喜欢哪种方法?的主要内容,如果未能解决你的问题,请参考以下文章

七种分布式全局 ID 生成策略,你更爱哪种?

七种分布式全局 ID 生成策略,你更爱哪种?

七种分布式全局 ID 生成策略,你更爱哪种?

我应该更喜欢哪种图像加载方法?

Vim 和 Emacs 文本编辑器:你更喜欢哪个?

您更喜欢哪种方法来改进 Maven 项目的增量构建?