如何使用ggplot2设置两个x轴和两个y轴

时间:2018-02-07 13:12:10

标签: r ggplot2 double axis heatmap

我的数据如下:

d <- data.frame(X=c('x1','x2','x3','x1','x2','x3','x1','x2','x3'),
                Y=c('y1','y1','y1','y2','y2','y2','y3','y3','y3'),
                Value=c(1,2,1,3,1,4,3,5,2))

我使用以下代码生成热图:

ggplot(d,aes(x=X,y=Y,fill=Value)) +
  geom_tile() +
  scale_fill_gradient2(low='green',mid='white',high='red',midpoint=3) +
  theme(axis.text.x = element_text(angle = 90),
        axis.text = element_text(size = 10),
        panel.background = element_blank()) +
  labs(x='',y='')

图表是:

enter image description here

但是,我的整个数据大约是500 * 500,因此x轴和y轴上的刻度太多,因此无法清楚地识别标签。但我必须保持所有的价值观。

所以我想使用双x轴和双y轴。例如,底部x轴仅保留标签x1,x3,x5 ......而顶部x轴仅保留标签x2,x4,x6 ....然后我对y轴执行相同操作。然后,图表看起来像:

enter image description here

我知道scale_x_continuous和sec.axis可能会这样做。但我的x和y是离散的。

有人可以帮助我,使图表看起来像第二个吗?

1 个答案:

答案 0 :(得分:1)

你是对的,你只能使用具有连续数据的辅助轴。一种解决方案是将x和y值转换为连续值以进行绘图(仅使用整数序列),但将离散的x和y值保存为矢量以用于标记轴。

在这里,我已经以一种可扩展到更大的实际数据集的方式分配了连续值。我已经为x和y创建了关键数据帧,以便将每个唯一的离散值与整数相匹配,而不是将这些关键数据帧与原始数据帧合并,因此每个离散的x和y值都会分配一个可用于绘图的数值。

#create key dataframes to assign an integer to each x and y value
key.df.x <- data.frame(X = unique(d$X), x.num = (1:length(unique(d$X))))
key.df.y <- data.frame(Y = unique(d$Y), y.num = (1:length(unique(d$Y))))

#merge key dataframes with original data
d <- merge(d, key.df.x, by = "X", all.x = TRUE)
d <- merge(d, key.df.y, by = "Y", all.x = TRUE)

#make label vectors from original variable names
xlabels = unique(d$X)
ylabels = unique(d$Y)

#select odd numbered elements for primary labels, even for secondary labels
xlabels.primary <- xlabels[seq(1, length(xlabels), by = 2)]
xlabels.secondary <- xlabels[seq(2, length(xlabels), by = 2)]
ylabels.primary <- ylabels[seq(1, length(ylabels), by = 2)]
ylabels.secondary <- ylabels[seq(2, length(ylabels), by = 2)]

ggplot(d,aes(x = x.num, y = y.num,fill=Value)) + #plot using continuous data
  geom_tile() +
  scale_fill_gradient2(low='green',mid='white',high='red',midpoint=3) +
  theme(axis.text.x = element_text(angle = 90),
        axis.text = element_text(size = 10),
        panel.background = element_blank()) +
  # set primary axis breaks to odd numbers, label with ylabels.primary
  scale_y_continuous(breaks = seq(1, max(d$y.num), by = 2), labels = ylabels.primary,
  # set secondary axis breaks to even numbers, label with ylabels.secondary                    
                      sec.axis = dup_axis(breaks = seq(2, max(d$y.num), by = 2),
                                         labels = ylabels.secondary)) +
  scale_x_continuous(breaks = seq(1, max(d$x.num), by = 2), , labels = xlabels.primary,
                     sec.axis = dup_axis(breaks = seq(2, max(d$x.num), by = 2),
                                         labels = xlabels.secondary)) +
  labs(x='',y='')

enter image description here