【问题标题】:There are more factors than what I have in the X axis being labeled有比我在 X 轴上标记的因素更多的因素
【发布时间】:2021-11-05 18:34:30
【问题描述】:

我正在绘制一个简单的小提琴图,显示一个变量的小提琴 2 年,所以我只需要“2017”和“2018”出现在 X 轴上,但从 2016.5、2017.0 开始出现更多刻度线, 2017.5... 直到 2018.5。在我数据的“年份”列中,我只有想要绘制的两年。我不明白为什么会这样显示。这是我的代码和我得到的图表图像!

enter image description here

sum.data <- ddply(df, .(Field), summarize, mean.TF = mean(TF, na.rm = T))

(violin <- 
    ggplot(df, aes(Year, TF)) +
    geom_violin(aes(fill = factor(Year))) +
    stat_summary(fun.y=mean, geom ="point", shape=18, size=2) +
    labs(x= NULL, y= "Total FAME") +
    facet_grid(Field ~.) +
    geom_hline(data = sum.data, aes(yintercept = mean.TF), linetype = 3) +
    scale_y_continuous(breaks = seq(0,300,50)) +
    theme.custom)

【问题讨论】:

  • 提供有关数据的更多信息。在 R 中运行此 dput(yourdf) 命令并将输出粘贴到此处。
  • 试试ggplot(df, aes(factor(Year), TF))
  • 第一行 - “年份”不是 aes(Year, TF) 中的一个因素,所以它是数字。使其成为数据框中的一个因素,然后您不必在绘图调用中担心它。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: r ggplot2 axis-labels x-axis


【解决方案1】:

这会起作用。

(violin <- df %>%
    mutate(Year = factor(Year)) %>%
    ggplot( aes(Year, TF)) +
    geom_violin(aes(fill = factor(Year))) +
    stat_summary(fun.y=mean, geom ="point", shape=18, size=2) +
    labs(x= NULL, y= "Total FAME") +
    facet_grid(Field ~.) +
    geom_hline(data = sum.data, aes(yintercept = mean.TF), linetype = 3) +
    scale_y_continuous(breaks = seq(0,300,50)) +
    theme.custom)

【讨论】:

  • 非常感谢!
【解决方案2】:

发生这种情况是因为Year 是一个数字变量,而 ggplot 根据这些值进行了分离,如果你有更多年可能不会发生这种情况。这里有两种解决方案。

示例数据

df <-
tibble(
  x = rep(2014:2015, each = 100),
  y = c(rnorm(100),rexp(100))
) 

原码

df %>% 
  ggplot(aes(x,y))+
  geom_violin(aes(fill = factor(x)))

解决方案

在一个因子/字符中转换年份

这是一个很好的解决方案,因为还解决了美学fill,它可能会使其他一些几何形状复杂化,但这是非常具体的。

df %>% 
  mutate(x = as.factor(x)) %>% 
  ggplot(aes(x,y))+
  geom_violin(aes(fill = x))

为 x 轴添加刻度

使用比例可以设置任何labelsbreaks,但您仍然需要为审美fill 转换变量。

df %>% 
  ggplot(aes(x,y))+
  geom_violin(aes(fill = factor(x)))+
  scale_x_continuous(breaks = 2014:2015)

结果

【讨论】:

  • 非常感谢!那行得通。我是新手,我的过程有点慢。非常感谢您的帮助!
猜你喜欢
  • 2018-11-18
  • 2013-04-27
  • 1970-01-01
  • 2020-05-03
  • 2022-01-13
  • 2018-12-10
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多