[英]X-Y Axis Formatting in R
我正在嘗試繪制圖形並對y軸進行格式化,以使數字具有適當的間距(相隔5,000)並被格式化為具有逗號(例如350,000)。 另外,我正在嘗試使x軸(日期)顯示更多細化,以便在x軸上有更多日期供查看者查看。 每次繪制圖表時,我都會在x軸上得到數字,而不是日期。
這就是我到目前為止
plot(date,sales,type="s",ylab="Sales",yaxt="n")
axis(1, at = seq(min(date), max(date), length.out = 1)
axis(2, at = seq(min(sales), max(sales), length.out = 20), labels = formatC(seq(min(revenue), max(revenue), length.out = 20),small.mark = " ", format = "d"), las = 2)
這是我正在使用的數據:
sales <- c(76103, 57300, 49875, 52113, 47891, 43531, 50909, 54182, 55884,
63780, 57165, 59841, 65952, 67602, 70693, 76375, 83365, 82051,
88568, 100717, 99344, 88980, 99034, 99593, 110497, 87223, 98350,
102337, 116642, 116854, 138072, 137737, 84696, 64028, 74457,
82260, 89841, 90251, 92486, 95298, 105186, 114004, 125486, 125330,
121609, 124053, 127363, 115706, 115173, 108807, 106469, 112372,
110860, 106773, 111647, 107490, 86029, 67618, 74113, 67344)
date <- structure(c(11292, 11382, 11474, 11566, 11657, 11747, 11839,
11931, 12022, 12112, 12204, 12296, 12387, 12478, 12570, 12662,
12753, 12843, 12935, 13027, 13118, 13208, 13300, 13392, 13483,
13573, 13665, 13757, 13848, 13939, 14031, 14123, 14214, 14304,
14396, 14488, 14579, 14669, 14761, 14853, 14944, 15034, 15126,
15218, 15309, 15400, 15492, 15584, 15675, 15765, 15857, 15949,
16040, 16130, 16222, 16314, 16405, 16495, 16587, 16679), class = "Date")
除非您的地塊很大(比屏幕大得多),否則您要求的標簽數將不可讀,因為它們會相互重疊。 遵循您所要求的精神(每5000個y標記,y標簽中的逗號,更有意義的x標簽):
# enlarge left margin to accommodate transposed labels
par(mar = c(5.1, 6.1, 2.1, 2.1))
# a sequence for tick marks
y_seq <- seq((min(sales) %/% 5000) * 5000,
(max(sales) %/% 5000 + 1) * 5000,
by = 5000)
# a sequence for labels
y_labs <- prettyNum(y_seq, big.mark = ',')
y_labs[seq(1, length(y_labs), 2)] <- NA
plot(date, sales, type="s", ylab=NA, xaxt = 'n', yaxt = 'n')
# `axis.Date` makes sequencing and formatting easy; adapt as you like
axis.Date(1, date, at = seq.Date(min(date), max(date), by = 'year'), format = '%Y')
axis(2, at = y_seq, labels = y_labs, las = 2)
# add y label in a readable location
title(ylab = 'Sales', mgp = c(4.5, 1, 0))
如果您想要更多標簽,則可以從此處自定義方法。
最后一點:盡管您總是可以與基本R圖形進行戰斗直到它們完成您想要的操作,但是當ggplot2
具有更好的默認值時,有時不值得進行這種戰斗。
僅兩行:
library(ggplot2)
qplot(date, sales, geom = 'step')
使
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.