如何设置两个x轴和使用GGPLOT2两个Y轴线(how to set two x axis and

2019-09-30 00:03发布

我的数据是这样的:

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='')

图为:

但是,我的整个数据大约是500 * 500,所以在X轴和Y轴太多的刻度,这样的标签是不可能清楚地认识。 但我不得不把所有的值。

所以我想使用双x轴和双Y轴。 例如,底部x轴只保存标贴X1,X3,X5 ......和顶部x轴只保存标签X2,X4,X6 ....然后我做同样的Y轴。 然后,图的样子:

我知道scale_x_continuous和sec.axis可能做到这一点。 但我的X和Y是离散的。

谁能帮我,这样的图形看起来像第二个?

Answer 1:

你是对的比你只能使用辅助轴连续数据。 一种解决方案是您的x和y值转换为连续值绘制(只使用整数的序列),但保存的离散x和y值作为矢量使用用于标记的轴。

在这里,我的方式,应该是扩展到你的大,实际的数据集分配连续的值。 我做了x和y的每一个独特的离散值与整数匹配,比原来的数据帧合并这些关键dataframes所以每个离散x和y的值赋予您可以使用绘图数值键dataframes。

#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='')



文章来源: how to set two x axis and two y axis using ggplot2