2017-09-19 195 views
0

我做了使用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") 

enter image description here

我有两个问题在这里:

  1. 我想更改标签的位置图表的最后一点,但我不知道如何。

  2. 标签有很多小数点的,我想改变,只是2

+0

你是什么意思“标签有很多小数点,我想改为2”? – PoGibas

+0

标签中的数字是:1.129865665,我想要1.13,明白了吗? –

+0

创建一个新的变量,并根据需要舍入数字,并将其用作标签变量。使用'round()'。 – dshkol

回答

0
  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做什么(无法​​测试我的代码)。

+0

最后一个函数从我的data.frame中获取列“relativo”的最后一个值。它运作良好,谢谢! –

+0

@DaniloImbimbo高兴地帮忙!我也学到了一些新的:-) – PoGibas