2016-10-06 28 views
1

最近作成したデータのヒストグラムを作成しています。データをより読みやすくするために、ティックラインに数値的にマークされた区間を有する。Q:R ggplot2 - 別々の目盛りの精度が異なる

これは、読みやすさに小さな問題を引き起こしています。下のコードを使用すると、平均値をフロート値として持つと、すべての目盛りが平均値と同じ精度になり、この場合、7がありますが、 3.5のようなものへの平均値は、1つの末尾に0を持っています。

誰もが手動で各マークのパーシッションを設定する方法を知っているのだろうかと思っていました。理想的には、0,1,2、..、10のマークを整数にしたいのですが、より正確な数値がリストされているので、平均値には2桁の精度が表示されます。

require(ggplot2) 
set.seed(1235) 

df <- data.frame(x=rexp(1000)) 

mean = mean(df$x) 

ggplot(df, aes(x=x)) + 
    geom_histogram(binwidth = .05, position="dodge", color="black", fill="transparent") + 
    geom_vline(data=df, aes(xintercept=mean), linetype="dashed", color="red") + 
    theme_bw() + 
    scale_x_continuous(name="Values", expand = c(0, 0), breaks = sort(c(seq(0,10,1), mean))) 

Image of the resultant graph from the code above.

答えて

1

あなたはscale_x_continuouslabelsパラメータを設定することができます。値は重複しているので、それに応じて調整するか、別の場所にラベルを貼ります。 geom_textである。

ggplot(df, aes(x = x)) + 
    geom_histogram(binwidth = .05, position = "dodge", color = "black", fill = "transparent") + 
    geom_vline(aes(xintercept = mean), linetype = "dashed", color = "red") + 
    theme_bw() + 
    scale_x_continuous(name="Values", expand = c(0, 0), 
         breaks = sort(c(seq(0,10,1), mean)), 
         labels = sort(c(0L:10L, round(mean, digits = 2)))) 

plot with fixed labels

+1

これは素晴らしい作品。ありがとうございました! – valeranth

+0

私の答えは@alistaireと似ていましたが、 'my_breaks < - sort(c(seq(0、10、1)、mean))' 'my_labels < - format(my_breaks、digits = 2)' –

関連する問題