如何在ggplot2中设置Y轴次要刻度线样式(虚线/细宽度)
修改ggplot2中Y轴次要刻度线的样式
用户使用以下ggplot2代码绘制K线类图表,希望调整Y轴次要刻度线的样式(比如设为虚线或比主刻度更细):
原代码:
library(ggplot2) width = as.numeric(dff$time_terminal[1]-dff$time_terminal[2])*22.5 ggplot(data =dff, aes(x = time_terminal)) + geom_rect(aes(xmin = time_terminal - width, xmax = time_terminal + width, ymin = pmin(open.ha, close.ha), ymax = pmax(open.ha, close.ha), fill = dir)) + geom_linerange(aes(ymin=low, ymax=high)) + geom_point(aes(y = close), size = 1)+ labs(title = paste(min(df$time_terminal), max(df$time_terminal)), y = "Close", x = "") + theme_tq()+ scale_y_continuous(breaks = seq(round(min(df$close),-1), max(df$close), by = 10))+ theme(legend.position="none")
数据集:
dff <- structure(list(time_terminal = structure(c(1663973640, 1663973700, 1663973760, 1663973820, 1663973880, 1663973940), class = c("POSIXct", "POSIXt"), tzone = "UTC"), open.ha = c(12310.0220066959, 12308.473503348, 12306.386751674, 12303.655875837, 12306.1654379185, 12308.9202189592 ), high = c(12311.3, 12310.3, 12303.8, 12316.8, 12321.3, 12312.8 ), low = c(12301.3, 12300.3, 12294.8, 12300.3, 12302.8, 12300.8 ), close.ha = c(12306.925, 12304.3, 12300.925, 12308.675, 12311.675, 12305.425), dir = c(FALSE, FALSE, FALSE, TRUE, TRUE, FALSE), close = c(12303.8, 12303.3, 12302.3, 12315.3, 12306.3, 12301.8 )), row.names = 23033:23038, class = "data.frame")
解决方案
通过ggplot2的theme()元素可以分别控制主刻度和次要刻度的样式,核心是使用axis.ticks.y(主刻度)和axis.minor.ticks.y(次要刻度)两个参数,自定义线条粗细、线型等属性。以下是修改后的完整代码:
library(ggplot2) library(tidyquant) # 加载theme_tq依赖包 width = as.numeric(dff$time_terminal[1]-dff$time_terminal[2])*22.5 ggplot(data =dff, aes(x = time_terminal)) + geom_rect(aes(xmin = time_terminal - width, xmax = time_terminal + width, ymin = pmin(open.ha, close.ha), ymax = pmax(open.ha, close.ha), fill = dir)) + geom_linerange(aes(ymin=low, ymax=high)) + geom_point(aes(y = close), size = 1)+ labs(title = paste(min(dff$time_terminal), max(dff$time_terminal)), y = "Close", x = "") + theme_tq()+ scale_y_continuous( breaks = seq(round(min(dff$close),-1), max(dff$close), by = 10), # 可选:自定义次要刻度位置,比如每5个单位一个次要刻度 minor_breaks = seq(round(min(dff$close),-1), max(dff$close), by = 5) )+ theme( legend.position="none", # 主Y轴刻度:粗实线 axis.ticks.y = element_line(size = 0.6, linetype = "solid"), # 次要Y轴刻度:细虚线 axis.minor.ticks.y = element_line(size = 0.2, linetype = "dashed") )
关键参数说明
axis.ticks.y:控制Y轴主刻度的样式,size设置线条粗细,linetype设置线型(solid为实线);axis.minor.ticks.y:控制Y轴次要刻度的样式,这里设为更细的线条(size=0.2)和虚线(linetype="dashed");minor_breaks:可选参数,用于自定义次要刻度的位置,若不设置则使用ggplot2默认的次要刻度生成逻辑。
内容的提问来源于stack exchange,提问作者gaut
相关产品推荐
相关产品推荐

