2015-05-24 112 views
0

这是我的代码。我用过ggplot2。我想改变是单独Y轴值在PIC下面提到如何更改qqplot中的y轴值

library(ggplot2) 
rm(list=ls()) 
bar=read.csv("Age.csv") 
attach(bar) 
Category=sub('\\s+$', '', Category) 

HSI = HSI-100 
df = data.frame(HSI=HSI,Category) 
ggplot(df, aes(x=Category,y=HSI, fill=Category)) + 
    geom_bar(stat = "identity", aes(width=0.3)) + # adjust width to change thickness 
    geom_text(aes(label=HSI+100, y=HSI+2*sign(HSI)),# adjust 1.1 - to change how far away from the final point the label is 
      size=5 # adjust the size of label text   
) 

enter image description here

+0

为什么从HSI中删除100,然后将100添加到geom_text? 它应该按照你的想法保持恒生指数的原始价值。 – xraynaud

+0

@xraynaud其实我想在barplot中的条应该从100开始。如果HSI值小于100并且反之亦然,它会显示下降... –

回答

1

您可以使用scale_y_continuous设置休息和相应的标签:

ggplot(df, aes(x=Category,y=HSI, fill=Category)) + 
    geom_bar(stat = "identity", aes(width=0.3)) + # adjust width to change thickness 
    geom_text(aes(label=HSI+100, y=HSI+2*sign(HSI)), size = 5) + 
    scale_y_continuous(breaks = seq(-20, 30, 10), labels = 100 + seq(-20, 30, 10)) 

这将产生你的所需的图形(以及警告消息:In loop_apply(n,do.ply):当ymin!= 0时,堆叠没有明确定义,在这种情况下可以忽略)。

+0

是否有任何方法将轴位置移动到y = 0到y = 100 ?所以我可以避免hsi = hsi-100,然后再加起来。 @ B.Shankar –

+0

@AbdulShiyas,可以这样做,我使用坐标变换,但它会不必要地使事情复杂化。 –

1

您不需要改变HSI。你只需要使用ylim()函数ggplot:

ggplot(df, aes(x=Category,y=HSI, fill=Category)) + 
geom_bar(stat = "identity", aes(width=0.3)) + 
geom_text(aes(label=HSI, y=HSI+2*sign(HSI)), 
size=5)+ 
ylim(100,130) 

编辑:上述解决方案不适用于geom_bar工作。

解决方案需要从尺度库中定义翻译功能。

library(scales) 
translate100_trans <- function() { 
    trans <- function(x) x - 100 
    inv <- function(x) x + 100 
    trans_new("translate100_trans", trans, inv) 
} 

ggplot(df, aes(x=Category,y=HSI, fill=Category)) + 
geom_bar(stat = "identity", aes(width=0.3)) + 
geom_text(aes(label=HSI, y=HSI+2*sign(HSI)), 
size=5)+scale_y_continuous(trans="translate100") 
+0

我不认为这会产生有用的结果。限制不包含“0”的y轴将导致条不会显示出来。您可以在'df < - data.frame(HSI = c(126,104,112,94,86),Category = factor(LETTERS [1:5]))' –

+0

正确。这工作geom_point,而不是geom_bar。我编辑了使用geom_bar的解决方案的答案。 – xraynaud