【问题标题】:ggplot axis ticks fall at center of bin value rather than at the bin limitsggplot 轴刻度落在 bin 值的中心而不是 bin 限制处
【发布时间】:2015-09-11 20:03:23
【问题描述】:

我有日期 (x) 和 y (值) 的数据 (x,y)。我按值将 y 拆分为 bin,并在每天为每个 bin 绘制一个点,该点的大小与当天落入每个 bin 的值的数量成正比。现在每天有 5 个 bin,每个 bin 中的值的数量都有一个计数。垃圾箱看起来像:

组:        值
鞋帮:         40-50
中上:30-40
中:             20-30
中下:10-20
下:           0-10

我想绘制 y 与 x,其中 x 轴是日期,y 轴刻度是箱(每天将堆叠 5 个点,点的大小与该箱中的值数成正比那天)。

我有用于绘图的 R 代码,但 y 轴标签的刻度直接位于图表上的点旁边。但是,我希望刻度线落在点之间,以便点包含在 bin 范围内,而不是与该 bin 的单个平均值相关联。

代码是:

breaks = c(5, 15, 25, 35, 45, 55)
ggplot(df, aes(x = df$date, y = df$group, size = df$count)) +
    geom_point(aes(color = df$count), alpha = 0.8, show_guide = FALSE) +
    scale_x_date(breaks = "2 weeks", minor_breaks = "1 day", labels = date_format("%m-%d-%Y")) +  
    scale_y_discrete(name = "Value", labels=c(round(breaks))) 

我尝试了几种不同的方法来更改 y 轴刻度位置,包括更改 scale_y_discrete 中的标签和中断或将 axis.ticks.y 添加到 theme(),但我似乎无法让标签移动即使标签显示正确的值,也可以在图表上的点之间。

谢谢,感谢您的任何建议!

【问题讨论】:

  • 您能否将dput(df) 的输出添加到您的问题中。

标签: r ggplot2 axis-labels binning


【解决方案1】:

嗯,这是一种方法,但它有点小技巧。

# create sample dataset- you should provide this...
set.seed(1)    # for reproducible example
df <- data.frame(date  = rep(as.Date("2015-01-01")+0:4, each=5),
                 group = LETTERS[1:5],
                 count = rpois(5*5, lambda=10))

library(ggplot2)
n.lvls <- length(levels(df$group))
ggplot(df, aes(x=date, y=as.integer(group)-0.5))+
  geom_point(aes(size=count), shape=21, fill="lightgreen")+
  scale_y_continuous(limits=c(0,n.lvls+0.5),breaks=1:n.lvls, labels=levels(df$group), expand=c(0,0))

ggplot 通过绘制因子代码(相当于as.integer(y))处理离散(分类)轴,然后用因子水平标记它们(在本例中为A - E)。如果您想转换所有可以显式转换为整数的内容,请减去 0.5,然后提供您自己的中断和级别。就像我说的,一个黑客......

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多