使用小数绘制并以百分比表示工具提示标签

时间:2017-08-07 06:05:22

标签: r ggplot2 tooltip plotly percentage

我希望使用ggplotly绘制折线图并以百分比表示数字。因此,之前的ggplot命令表示百分比中的数字以及小数点后的。情节似乎有所不同。如何使用小数制作绘图并以百分比表示工具提示标签?

library(plotly)
library(ggplot2)
library(devtools)
library(proto)
library(RColorBrewer)
library(gapminder)
library(stringr)
library(broom)
library(mnormt)

dat1 <- data.frame(
sex = factor(c("Female","Female","Male","Male")),
time = factor(c("Lunch","Dinner","Lunch","Dinner"), 
levels=c("Lunch","Dinner")),
total_bill = c(13.53, 16.81, 16.24, 17.42)
total_bill_pr = sprintf("%.0f%%", 100 * total_bill)
)

# Map sex to different point shape, and use larger points
p <- ggplot(data=dat1, aes(x=time, y=total_bill_pr, group=sex, shape=sex)) +
geom_line() +
geom_point()

p <- ggplotly(p)
p

 # Map sex to different point shape, and use larger points
p <- ggplot(data=dat1, aes(x=time, y=total_bill, group=sex, shape=sex)) +
geom_line() +
geom_point()

p <- ggplotly(p)
p

1 个答案:

答案 0 :(得分:0)

以下是您的问题的解决方案:

library(plotly)
library(ggplot2)

total_bill = c(13.53, 16.81, 16.24, 17.42)
dat1 <- data.frame(
sex = factor(c("Female","Female","Male","Male")),
time = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill_no_pr = total_bill,
total_bill = sprintf("%.2f%%", total_bill)
)

# Use an additional "label" aesthetic
p <- ggplot(data=dat1, aes(x=time, y=total_bill_no_pr, 
            group=sex, shape=sex, label=total_bill)) +
     geom_line() + geom_point() + ylab("Total bill") + xlab("Time")

# Specify which aesthetic mappings to show in the tooltip 
p <- ggplotly(p, tooltip = c("x", "label", "group"))
p

enter image description here

更灵活的解决方案是:

# Use an additional "text" aesthetic
p <- ggplot(data=dat1, aes(x=time, y=total_bill_no_pr, group=sex, shape=sex,
            text=paste("Time:",time,"<br />Total bill:",total_bill,"<br />Sex:",sex))) +
     geom_line() + geom_point() + ylab("Total bill") + xlab("Time")

# Specify to show only the "text" aesthetic in the tooltip 
p <- ggplotly(p, tooltip = c("text"))
p

enter image description here