R:折线图与文本标签重叠

时间:2016-07-19 03:47:51

标签: r charts ggplot2 shiny plotly

我在Shiny中使用plotly创建了一个折线图。现在,在线图中,如果我想添加标签,它们与线条重叠,这使得难以理解。

我使用以下代码:

     a = paste("$",prettyNum(de$Amount, big.mark = ",", scientific = FALSE), sep = "")
      f <- list(

        size = 14,
        color = "Black",
        fontface="bold"
      )
      xQuartAxis <- list(
        title = "Month")
      yQuartAxis <- list(
        title = "Amount in $")
      plot_ly(
        x = as.vector(de$Month),
        y = de$Amount,
        text = paste(a), hoverinfo = "text", textinfo="text",showlegend = FALSE,
        name = "Amount Paid",
        mode = "lines+text"
      )%>%

        layout(title=paste("Monthly Amount paid by", clientName,"for the year",selectedYear, sep = " ") ,titlefont =f,t = 150,  xaxis = xQuartAxis, yaxis = yQuartAxis)
})

我收到了这个输出:

Click To View Output

请告诉我如何将文字与折线图分开以获得更好的曝光度?

谢谢:)

1 个答案:

答案 0 :(得分:1)

我建议让这些数字相对于该线突出。首先,使线条透明(例如,alpha = 0.2)。该线仍然可见,引导您的眼睛,但数字将突出显示。

其次,将数字截断为数千,以匹配y标度。您不需要为点标记显示这么多位数。

这是ggplotly版本,因为我不确定如何单独设置文本标记的不透明度和plot_ly的行。您可以在opacity=0.3内添加plot_ly(),但这样也可以使文字标记透明。

library(scales)
library(ggplot2)
library(plotly)

# Fake data
set.seed(395875)
de = data.frame(Month=factor(month.abb, levels=month.abb), Amount=rnorm(12, 12000, 1000))

ggplotly(
  ggplot(de, aes(Month,Amount)) +
    geom_line(aes(group=1), alpha=0.2, color="blue") + 
    geom_text(aes(label=paste0("$", sprintf("%1.1f", Amount/1000))), size=3.5) +
    theme_bw() +
    scale_y_continuous(limits=c(0, max(de$Amount)), breaks=seq(0,15000,5000), 
                       labels=paste0("$",seq(0,15000,5000)/1000,"k")) +
    labs(y="Amount ($000)")
)

enter image description here