简体   繁体   English

控制 ggplot2 (scale_x_discrete) 中的离散刻度标签

[英]Control Discrete Tick Labels in ggplot2 (scale_x_discrete)

On a continuous scale, I can reduce the density of the tick labels using breaks and get nice control over their density in a flexible fashion using scales::pretty_breaks() .在连续尺度上,我可以使用breaks来降低刻度标签的密度,并使用scales::pretty_breaks()以灵活的方式很好地控制它们的密度。 However, I can't figure out how to achieve something similar with a discrete scale.但是,我不知道如何用离散的比例实现类似的东西。 Specifically, if my discrete labels are letters , then let's say that I want to show every other one to clean up the graph.具体来说,如果我的离散标签是letters ,那么假设我想每隔一个显示一个以清理图表。 Is there an easy, systematic way to do this?有没有一种简单、系统的方法来做到这一点?

I have a hack that works (see below) but looking for something more automatic and elegant.我有一个可行的技巧(见下文),但正在寻找更自动和优雅的东西。

library(tidyverse)

# make some dummy data
dat <-
  matrix(sample(100),
         nrow = 10,
         dimnames = list(letters[1:10], LETTERS[1:10])) %>%
  as.data.frame() %>%
  rownames_to_column("row") %>%
  pivot_longer(-row, names_to = "column", values_to = "value")

# default plot has all labels on discrete axes
dat %>% 
  ggplot(aes(row, column)) +
  geom_tile(aes(fill = value))

# desired plot would look like following:
ylabs <- LETTERS[1:10][c(T, NA)] %>% replace_na("")
xlabs <- letters[1:10][c(T, NA)] %>% replace_na("")

# can force desired axis text density but it's an ugly hack
dat %>% 
  ggplot(aes(row, column)) +
  geom_tile(aes(fill = value)) +
  scale_y_discrete(labels = ylabs) +
  scale_x_discrete(labels = xlabs)

Created on 2021-12-21 by the reprex package (v2.0.1)代表 package (v2.0.1) 于 2021 年 12 月 21 日创建

One option for dealing with overly-dense axis labels is to use n.dodge :处理过度密集的轴标签的一种选择是使用n.dodge

ggplot(dat, aes(row, column)) +
  geom_tile(aes(fill = value)) +
  scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
  scale_y_discrete(guide = guide_axis(n.dodge = 2))

带有躲避轴标签的ggplot

Alternatively, if you are looking for a way to reduce your use of xlabs and do it more programmatically, then we can pass a function to scale_x_discrete(breaks=) :或者,如果您正在寻找一种方法来减少对xlabs的使用并以更多的方式进行编程,那么我们可以将 function 传递给scale_x_discrete(breaks=)

everyother <- function(x) x[seq_along(x) %% 2 == 0]
ggplot(dat, aes(row, column)) +
  geom_tile(aes(fill = value)) +
  scale_x_discrete(breaks = everyother) +
  scale_y_discrete(breaks = everyother)

具有交替标签去除的ggplot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM