【问题标题】:How to change decimal points on chart label and change the label position?如何更改图表标签上的小数点并更改标签位置?
【发布时间】:2017-09-20 04:05:35
【问题描述】:

我使用ggplot2 制作了一个图表,显示了一些历史数据:

library(ggplot2)
chart_2 <- ggplot(graf2, aes(x=data, y=relativo, label = as.integer(relativo))) + 
scale_fill_discrete(guide = F) +
geom_line(aes(y=relativo, color="red"), size = 0.7) +
labs(title = "Relativo Preço Gasolina: Consumidor/Distribuidora", x = "Data", y="Relativo de Preços") +
theme_bw() +
theme(legend.position = "none", plot.title = element_text(hjust=0.5, size = 12, face = "bold"), 
axis.text.x=element_text(angle=90,vjust=0.5, size = 10, color = "black"), 
axis.title=element_text(size = 12)) +
scale_x_date(date_labels = "%b %Y", date_breaks = "1.5 years") +
geom_dl(aes(label=last(relativo)), vjust = -2, method="last.points")

我这里有两个问题:

  1. 我想改变标签在图表最后一点的位置,但不知道怎么做。

  2. 标签有很多小数点,我想改成2个。

【问题讨论】:

  • “标签有很多小数点,我想改成2”是什么意思?
  • 标签中的数字是:1.129865665,我想成为 1.13,明白了吗?
  • 创建一个新变量,其中的数字根据需要四舍五入,并将其用作标签变量。使用round()

标签: r ggplot2 charts label


【解决方案1】:
  1. 使用position_nudge改变标签调整参数position的位置:

    # Using -2 only as example to move label along x-axis
    geom_dl(aes(label = last(relativo)), 
            method = "last.points",
            position = position_nudge(-2))
    
  2. 要更改为两位小数,请使用round function from base R

     round(last(relativo), 2)
    

组合代码应该是:

geom_dl(aes(label = round(last(relativo), 2), 
        method = "last.points",
        position = position_nudge(-2))

PS.:我不知道你的函数 last 做了什么(无法​​测试我的代码)。

【讨论】:

  • 最后一个函数从我的 data.frame 中获取“relativo”列的最后一个值。效果很好,谢谢!
  • @DaniloImbimbo 乐于助人!我还学到了一些新东西:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
相关资源
最近更新 更多