X轴与条形图不匹配 [英] X axis does not match barplot

查看:138
本文介绍了X轴与条形图不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用barplot()函数从矩阵创建堆叠图表.

I used barplot() function to create a stacked chart from matrix.

矩阵看起来像这样:

1 0.989013 0.010987
2 0.999990 0.000010
3 0.999990 0.000010
4 0.999990 0.000010

用于创建堆积图的代码如下:

code to create a stacked chart looks like this:

barplot(t(as.matrix(x)), col=c("cyan", "black"))

问题是我想在某些点创建带有刻度和标签的自定义x轴.我使用以下方法创建x轴:

The problem is that I want to create custom x axis with ticks and labels at certain points. I used following to create x axis:

axis(1, at=keyindexes, labels=unique(t$V4), tck=-0.01)

其中keyindexes是条形数字的矢量,我需要有刻度线,而unique(t $ V4)是包含每个刻度线唯一名称的矢量.

where keyindexes is vector of bar numbers where I need to have ticks and unique(t$V4) is vector containing unique name for each tick.

现在的问题是x轴与图表区域不匹配,并且明显更短.谁能建议如何使x轴更长?

Now the problem is that x axis does not match with chart area and is significantly shorter. Can anyone advice on how to make x axis longer?

推荐答案

轴标签的问题实际上是条形图不以整数为中心. 例如,用十行制作一些数据,然后用barplot()绘制它们.然后为x轴添加axis(),其编号为1到10.

The problem with axis labels is in fact that bars are not centered on whole numbers. For example, make some data with ten rows and plot them with barplot(). Then add axis() for x axis at numbers from 1 to 10.

set.seed(1)
x<-data.frame(v1=rnorm(10),v2=rnorm(10))
barplot(t(as.matrix(x)), col=c("cyan", "black"))
axis(1,at=1:10)

现在的轴文本位置不正确.

Now axis texts are not in right position.

要解决此问题,应将barplot()保存为对象,并将该对象用作轴上的at=值.

To correct this problem, barplot() should be saved as object and this object should be used as at= values in axis.

m<-barplot(t(as.matrix(x)), col=c("cyan", "black"))
m
 [1]  0.7  1.9  3.1  4.3  5.5  6.7  7.9  9.1 10.3 11.5
axis(1, at=m,labels=1:10)

如果仅应绘制一些轴刻度文本,则可以子集所需的m值并提供相同长度的labels=.在此示例中,仅注释了1.,5和10.条.

If only some of axis ticks texts should be plotted then you can subset m values that are needed and provided the same length of labels=. In this example only 1., 5. and 10. bars are annotated.

m<-barplot(t(as.matrix(x)), col=c("cyan", "black"))
lab<-c("A","B","C")
axis(1, at=m[c(1,5,10)],labels=lab)

这篇关于X轴与条形图不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆