【问题标题】:Left/right and bottom/top axes manipulation in Ggplot2Ggplot2中的左/右和下/上轴操作
【发布时间】:2020-08-20 02:34:14
【问题描述】:

我正在尝试使用“axis.line.y.right”来操纵右 Y 轴,但轴没有改变。我使用了以下主题,但只有左侧 Y 轴和底部 X 轴根据所需的参数更改了它们的颜色和大小。我不知道我做错了什么。非常感谢。

 C57.sum
 Genotype Group Strain   my_mean CI.plus CI.minus  my_n
 WT       C57BL C57BL/6J   0.403   0.482    0.319    12





my.theme = list(theme(axis.line.y.left = element_line(size = 3, color = "red"),
                      axis.line.y.right = element_line(size = 3, color = "red"),
                      axis.line.x.top =  element_line(size = 3, color = "red"),
                      axis.line.x.bottom = element_line(size = 3, color = "red")),
                ylim(0,5))


Plot <- ggplot() +
  
  geom_bar(data = C57.sum, 
           aes(y = my_mean, x = Strain, fill=Group),
           color="black", stat="identity", width = 0.6, show.legend = FALSE,
           position = position_dodge2(preserve = "single")) + 
  
  geom_linerange(data = C57.sum, 
                 aes(x = Strain, ymin = CI.minus, ymax = CI.plus),
                 color = "black", size = 0.42, 
                 position = position_dodge2(preserve = "single", width = 0.6)) +
  

  geom_text(data = C57.sum, 
            aes(y = 0, x = Strain, group = Group, label=paste0("n = ",my_n), vjust=1.4),
            size = 2.8, fontface = "italic", position = position_dodge(0.6)) +
  
  coord_fixed(ratio=4/5) +
  my_theme.2

  Plot

【问题讨论】:

  • 如果没有看到生成绘图的其余代码,您的问题是不可重现的,尽管我想ylim(0, 5) 可能与它有关(它可能覆盖了scale_y_** 的早期行其中包括右 y 轴的规格)。
  • 感谢您的评论...我已添加其余代码
  • 我们没有您的数据。可以使用 R 中可用的通用数据集(例如 mtcars)来表示此问题吗?

标签: r ggplot2


【解决方案1】:

在影响这些轴的主题元素生效之前,您必须先在右侧和顶部添加轴。如果没有生成顶部或右侧轴,则不会绘制它们。下面是使用guides() 函数和sec.axis 参数的两个示例。

library(ggplot2)

my.theme = list(theme(axis.line.y.left = element_line(size = 3, color = "red"),
                      axis.line.y.right = element_line(size = 3, color = "red"),
                      axis.line.x.top =  element_line(size = 3, color = "red"),
                      axis.line.x.bottom = element_line(size = 3, color = "red")))


ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  guides(x.sec = "axis", y.sec = "axis") +
  my.theme


ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  scale_x_continuous(sec.axis = sec_axis(~.x)) +
  scale_y_continuous(sec.axis = sec_axis(~.x)) +
  my.theme

reprex package (v0.3.0) 于 2020 年 8 月 20 日创建

或者,您也可以设置例如scale_x_continuous(position = "top"),但不会绘制底部坐标轴。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多