【问题标题】:ggplot2 - how to limit panel and axis?ggplot2 - 如何限制面板和轴?
【发布时间】:2019-10-31 10:13:54
【问题描述】:

我想知道这个情节怎么转:

进入这个情节:

如您所见,第二张图上的面板和轴仅限于数据范围。我使用设计软件制作了第二张图,但想知道代码。

我已经使用限制了 x 和 y 轴

xlim 和 ylim 但没有区别。

请看我下面的代码,很抱歉,第一次使用 r studio。谢谢!

ggplot() +
  geom_errorbar(data = U1483_Coiling_B_M_Removed_R, mapping = aes(x = `Age (Ma) Linear Age Model`, ymin = `Lower interval*100`, ymax = `Upper interval*100`), width = 0.025, colour = 'grey') +
  geom_line(data = U1483_Coiling_B_M_Removed_R, aes(x = `Age (Ma) Linear Age Model`, y = `Percent Dextral`)) +
  geom_point(data = U1483_Coiling_B_M_Removed_R, aes(x = `Age (Ma) Linear Age Model`, y = `Percent Dextral`), colour = 'red') +
  geom_point(data = U1483_Coiling_B_M_Removed_R, aes(x = `Age (Ma) Linear Age Model`, y = `Lab?`)) +
  theme(axis.text.x=element_text(angle=90, size=10, vjust=0.5)) +
  theme(axis.text.y=element_text(angle=90, size=10, vjust=0.5)) +
  theme_classic() +
  theme(panel.background = element_rect(colour = 'black', size = 1)) +
  xlim(0, 2.85) +
  ylim(0, 100)

【问题讨论】:

  • 将xlim 和ylim 包裹在coord_cartesian(xlim =c(0, 3), ylim = c(0, 100)) 内有帮助吗?如果没有,您需要提供一些示例数据。
  • 嗨,不,没有区别。关于样本数据,x 轴上显示的数据范围在 0 到 100 之间,y 轴上的数据范围从 0 开始。(注意照片中我已将绘图翻转 90 度)。我的问题是为什么轴和面板会超出这个范围?
  • @CrypticSpecies 对于未来的问题,提供一个玩具数据集真的很有帮助,我们可以用它来演示解决方案,而不必创建自己的解决方案。您可以使用dput 创建可以包含在您的问题中的可复制粘贴输出。另外,如果您将U1483_Coiling_B_M_Removed_R 作为ggplot 的参数,那么您不需要在每个geom 中都包含它
  • 嗨,谢谢你以后会做的。

标签: r ggplot2


【解决方案1】:

您可以在指定轴刻度时使用expand,如下所示:

# Load library
library(ggplot2)

# Set RNG
set.seed(0)

# Create dummy data
df <- data.frame(x = seq(0, 3, by = 0.1))
df$y <- 100 - abs(rnorm(nrow(df), 0, 10))

# Plot results
# Original
ggplot(df, aes(x, y)) + 
  geom_line() +
  geom_point(colour = "#FF3300", size = 5) 

# With expand
ggplot(df, aes(x, y)) + 
  geom_line() +
  geom_point(colour = "#FF3300", size = 5) +
  scale_y_continuous(expand = c(0, 0))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多