使R中的X轴标签更精细

时间:2015-06-04 20:38:04

标签: r axis-labels graphing

我正在生成一个图形和R,并希望x轴更精细。

  Tenure         Type Visits Members   Percent
1      0        Basic 122446  283975 0.4311858
2      0      Premium  21190   44392 0.4773383
3      1        Basic  92233  283975 0.3247927
4      1      Premium  17909   44392 0.4034285
5      2        Basic  42516  283975 0.1497174
6      2      Premium   9613   44392 0.2165480


 plot(Visit_Curve$Tenure, Visit_Curve$Percent, type = "n", main = "Visit Curve")
    lines(Visit_Curve$Tenure[Visit_Curve$Type == "Basic"], Visit_Curve$Percent[Visit_Curve$Type == "Basic"], col = "red")
    lines(Visit_Curve$Tenure[Visit_Curve$Type == "Premium"], Visit_Curve$Percent[Visit_Curve$Type == "Premium"], col = "blue")

上面的代码生成的图表的x轴按因子50细分。有没有办法在基础R绘图中轻松自定义比例?也许每10或5个刻度?

谢谢, 本

1 个答案:

答案 0 :(得分:3)

只需使用axes = FALSE?axis

制作自定义轴

您可以大幅清理代码:

Visit_Curve <- read.table(header = TRUE, text = "Tenure         Type Visits Members   Percent
1      0        Basic 122446  283975 0.4311858
2      0      Premium  21190   44392 0.4773383
3      1        Basic  92233  283975 0.3247927
4      1      Premium  17909   44392 0.4034285
5      2        Basic  42516  283975 0.1497174
6      2      Premium   9613   44392 0.2165480")

with(Visit_Curve, {
  plot(Tenure, Percent, type = 'n', main = 'Visit Curve', axes = FALSE)
  axis(1, at = seq(0, 2, by = .15))
  axis(2, at = seq(.15, .45, by = .05), las = 1)
  box('plot')
  lines(Tenure[Type == 'Basic'], Percent[Type == 'Basic'], col = 'red')
  lines(Tenure[Type == 'Premium'], Percent[Type == 'Premium'], col = 'blue')
})

或使用xaxt = 'n'yaxt = 'n'

单独抑制每个轴上的标签
with(Visit_Curve, {
  plot(Tenure, Percent, type = 'n', main = 'Visit Curve', xaxt = 'n', las = 1)
  axis(1, at = seq(0, 2, by = .15))
  lines(Tenure[Type == 'Basic'], Percent[Type == 'Basic'], col = 'red')
  lines(Tenure[Type == 'Premium'], Percent[Type == 'Premium'], col = 'blue')
})

enter image description here

或使用ggplot2

library('ggplot2')
ggplot(Visit_Curve, aes(Tenure, Percent, colour = Type)) +
  geom_line() +
  scale_x_continuous(breaks = seq(0, 2, .15)) + 
  labs(title = 'Visit Curve')

enter image description here