2015-05-24 115 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