ggplot2 displaying unlabeled tick marks between labeled tick marks

孤街醉人 提交于 2020-07-30 08:55:43

问题


I've been having issues displaying minor tick marks on my histogram plot. I've tried the idea of plotting unlabeled major tick marks, but the tick marks wouldn't display. My code is pretty cumbersome and probably has some redundant lines. Any help would be appreciated.

ggplot(data=Shrimp1, aes(Shrimp1$Carapace.Length))+
geom_histogram(breaks=seq(3.5, 25, by=0.1),
             col="black",
             fill="gray", 
             alpha=1)+ 

 labs(title="Total Female Carapace Length")+
 labs(x="Carapace Length (mm)", y="# of Shrimp")+
  xlim(c(3.5, 25))+
  theme_bw()+
scale_y_continuous(expand = c(0,0),
                     limits = c(0,200))+
scale_x_continuous(breaks=seq(2.5,25,2.5))+

theme(axis.text.x=element_text(size=30,angle=45,hjust=1))+
  theme(plot.title=element_text(size=30, hjust=0.5))+
  theme(axis.text=element_text(size=30, color = "black"), 
        axis.title=element_text(size=30,face="bold"))+
  theme(panel.grid.major=element_line(colour="white"), 
        panel.grid.minor = element_line(colour = "white"))+
  theme(panel.border=element_blank())+
  theme(axis.ticks.x = (element_line(size=2)), 
        axis.ticks.y=(element_line(size=2)))+
  theme(axis.ticks.length=unit(.55, "cm"))+
  theme(panel.border=element_blank(), axis.line.x=element_line(colour="black"),
        axis.line.y=element_line(colour="black"))

Major ticks are present but I need minor ticks between them at intervals of 0.1

1


回答1:


I don't think you can add ticks to minor breaks, but you can have unlabeled major ticks, as you were thinking, by labeling them explicitly in scale_x_continuous. You can set the "minor" tick labels to blank using boolean indexing with mod (%%).

Similarly, you can set the tick sizes explicitly in theme if you want the "minor" ticks to be a different size.

set.seed(5)
df <- data.frame(x = rnorm(500, mean = 12.5, sd = 3))

breaks <- seq(2.5, 25, .1)

labels <- as.character(breaks)
labels[!(breaks %% 2.5 == 0)] <- ''
tick.sizes <- rep(.5, length(breaks))
tick.sizes[(breaks %% 2.5 == 0)] <- 1

df %>% 
  ggplot(aes(x)) +
  geom_histogram(binwidth = .1, color = 'black', fill = 'gray35') +
  scale_x_continuous(breaks = breaks, labels = labels, limits = c(2.5,25)) +
  theme_bw() +
  theme(panel.grid = element_blank(), 
        axis.ticks.x = element_line(size = tick.sizes))

Also as you might notice from my code, you can just call theme() once and put all the theme modifications into that one call.

Plot



来源:https://stackoverflow.com/questions/46412250/ggplot2-displaying-unlabeled-tick-marks-between-labeled-tick-marks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!