简体   繁体   English

根据数据中的另一列在 ggplot 中绘制辅助 x 轴

[英]Plotting a secondary x-axis in ggplot based on another column in the data

I am struggling to find if it is possible to plot a secondary x-axis (on the top of the linegraph if possible) using an entirely different column in the dataset.我正在努力寻找是否有可能使用数据集中完全不同的列来 plot 次要 x 轴(如果可能,在线图的顶部)。 I've been looking for a while, so apologies if this has been answered already.我已经找了一段时间了,如果这个问题已经得到解答,我深表歉意。 For example:例如:

Day <- c(1:10)
Revenue <- c(100,200,300,400,550,600,750,800,975,1000)
Date <- c("1/1","1/5","1/10","1/11","1/14","1/15","1/18","1/21","1/28","1/31")
a <- data.frame(Day,Revenue,Date)

I can plot "Day" on the x-axis and "Revenue" on the y-axis:我可以 plot x 轴上的“日”和 y 轴上的“收入”:

ggplot(a,(aes(Day,Revenue))) + geom_line(aes(y = Revenue))

However, is it possible to have the corresponding "Date" included at the top of the graph on a secondary x-axis that matches the primary x-axis ("Day")?但是,是否可以在与主 x 轴(“日”)匹配的辅助 x 轴上的图表顶部包含相应的“日期”? Thank you in advance for any help on this!预先感谢您对此的任何帮助!

One option to achieve your desired result would be to make use of dup_axis and use a labeller function which assigns the value from your Date column to values of Day chosen as breaks for the primary scale:实现所需结果的一种选择是使用dup_axis并使用贴标机 function 将Date列中的值分配给选择作为主要刻度中断的Day值:

library(ggplot2)

dup_labels <- function(x) a$Date[match(x, a$Day)]

ggplot(a,(aes(Day,Revenue))) + geom_line(aes(y = Revenue)) +
  scale_x_continuous(breaks = 1:10, sec.axis = dup_axis(labels = dup_labels))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM