mirror_ticks函数不适用于ggplot

时间:2018-12-09 00:42:05

标签: r ggplot2

我想在图表的所有四个边上打勾。建议的方式是mirror_ticks

library(ggplot2)
library(ggplotTicks)

sp6<-ggplot(Anna_Smooth, aes(y=log10(Prob2), x=log10(AvSize)))+
  geom_point( data=Anna_Smooth, aes(y=log10(Prob2), x=log10(AvSize), color=PART) )+ 
  guides( color=FALSE)


sp8<-sp6+ labs(x=expression(paste(log(s))))+
  labs(y=expression(paste(log(P(s))))   )+
  theme(axis.text.y   = element_text(size=14),
        axis.text.x   = element_text(size=14),
        axis.title.y  = element_text(size=15),
        axis.title.x = element_text(size=15),
        panel.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.line = element_line(colour = "black"),
        panel.border = element_rect(colour = "black", fill=NA, size=2)
)


sp10<-mirror_ticks(sp10, allPanels=TRUE)

我的输出sp10在相对的面板上没有刻度,如果我将allPanels=TRUE放在相同的结果 enter image description here

有修复程序吗?我愿意学习主题设置如何做到这一点?

1 个答案:

答案 0 :(得分:2)

ggplot2版本2.2.0(2016-11-11)开始,scale_x_continuous()scale_y_continuous()可以显示与主轴相反的副轴,并且可以由sec.axis参数控制。

这可以用来反映刻度线。

OP没有提供可重复的数据,因此我们使用mpg软件包随附的ggplot2数据集:

没有镜像刻度线的图表

library(ggplot2)
g1 <- ggplot(mpg, aes(log10(displ), log10(hwy))) +
  geom_point() +
  theme(
    axis.text.y   = element_text(size = 14),
    axis.text.x   = element_text(size = 14),
    axis.title.y  = element_text(size = 15),
    axis.title.x  = element_text(size = 15),
    panel.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    axis.line = element_line(colour = "black"),
    panel.border = element_rect(
      colour = "black",
      fill = NA,
      size = 2
    )
  ) 
g1

enter image description here

带有辅助轴的图表

g1 + 
  scale_x_continuous(sec.axis = dup_axis()) + 
  scale_y_continuous(sec.axis = dup_axis())

enter image description here

g1 + 
  scale_x_continuous(sec.axis = dup_axis(name = NULL)) + 
  scale_y_continuous(sec.axis = dup_axis(name = NULL))

enter image description here

g1 + 
  scale_x_continuous(sec.axis = dup_axis(name = NULL, labels = NULL)) + 
  scale_y_continuous(sec.axis = dup_axis(name = NULL, labels = NULL))

enter image description here

具有log10刻度的镜像刻度线

辅助轴也可以通过scale_x_log10()scale_x_log10()功能使用。

因此,可以避免在对log()的调用中使用aes()函数,而是通过指定适当的对数刻度:

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  theme(
    axis.text.y   = element_text(size = 14),
    axis.text.x   = element_text(size = 14),
    axis.title.y  = element_text(size = 15),
    axis.title.x = element_text(size = 15),
    panel.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    axis.line = element_line(colour = "black"),
    panel.border = element_rect(
      colour = "black",
      fill = NA,
      size = 2
    )
  ) +
  scale_x_log10(sec.axis = dup_axis(name = NULL, labels = NULL)) + 
  scale_y_log10(sec.axis = dup_axis(name = NULL, labels = NULL))

enter image description here