我使用
ggplot2
和 ggplotly
绘制了给定变量的密度图(每个人口普查区的人口,分为两组)。工具提示显示变量的小数点后六位:
每个人口普查区的人数:16.684932
但是,我希望它显示整数:
每个人口普查区的人数:17
代码:
### create dummy data
# normal distribution
rnorm1 <- rnorm(200, mean=10, sd=3)
# dataframe with the urban/rural labels and normal distribution
data <- data.frame(spatial_type = rep(c("1: urban", "2: rural"), each = 200 / 2),
persons_per_census_tract = rnorm1)
# define a function to combine several histograms in one plot, inspired by
# https://stackoverflow.com/a/53680101
# here already defining some parts of the appearance (y axis, outline size, colour via scale_fill_manual)
plot_multi_histogram <- function(df, feature, label_column) {
plt <- ggplot(df, aes(x=!!sym(feature),
fill=!!sym(label_column)),
text=paste(scales::percent(!!sym(feature)), "persons/census tract")) +
scale_fill_manual(
values=c("#9BB7B0", "#2DC6D6"),
breaks=c("1: urban", "2: rural")) +
geom_density(alpha=.7, size = .2) +
scale_y_continuous(labels = scales::unit_format(scale = 100, unit = "%")) +
labs(x=feature, y="density")
plt <- plt + guides(fill=guide_legend(title=label_column))
# Convert ggplot to a plotly object
plt <- ggplotly(plt, tooltip=c(feature))
return(plt)
}
# revert factor order of spatial_type to determine rendering order
# https://stackoverflow.com/a/43784645
data$spatial_type <- factor(data$spatial_type, c("2: rural", "1: urban"))
# Apply the function to create the plot based on dummy data
density.p <- plot_multi_histogram(data, 'persons_per_census_tract', 'spatial_type')
# print the plot
plotly::ggplotly(density.p)
我尝试在定义函数的代码中包含几个选项
plot_multi_histogram <- ...
,例如尺度::百分比
text=paste(scales::percent(!!sym(feature)), "persons/census tract")
text=paste(as.integer(!!sym(feature)), "persons/census tract")
round()
。
我认为舍入尝试失败是因为它们嵌入在函数中。有任何想法吗?谢谢!
第一个问题是你已经设置了
tooltip=feature
。因此,工具提示的值取自数据集的原始 feature
列。这就是为什么改变 text=...
中的任何内容都没有效果的原因。其次,您已将 text=
放在 aes()
中的 ggplot()
之外。好吧,在 ggplot()
的情况下,aes()
之外的所有参数都将被默默忽略。如果您想使用 !!sym()
从数据列创建工具提示,则必须在 aes()
内执行此操作。
不幸的是,简单地将
text=
移到 aes()
内也无法解决问题,因为只有在 geom
使用 stat="identity"
时才可以正常工作。也许有一种我不知道的更直接的方法。但一种修复方法是使用 text
设置和格式化工具提示 after_stat
,当然还可以在 tooltip="text"
中设置 ggplotly
:
library(ggplot2)
library(plotly)
set.seed(123)
plot_multi_histogram <- function(df, feature, label_column) {
plt <- ggplot(df, aes(
x = !!sym(feature),
fill = !!sym(label_column)
)) +
scale_fill_manual(
values = c("#9BB7B0", "#2DC6D6"),
breaks = c("1: urban", "2: rural")
) +
geom_density(
aes(text = after_stat(
paste(
scales::number(x, accuracy = 1), "persons/census tract"
)
)),
alpha = .7, size = .2
) +
scale_y_continuous(labels = scales::unit_format(scale = 100, unit = "%")) +
labs(x = feature, y = "density")
plt <- plt + guides(fill = guide_legend(title = label_column))
ggplotly(plt, tooltip = "text")
}
data$spatial_type <- factor(data$spatial_type, c("2: rural", "1: urban"))
plot_multi_histogram(data, "persons_per_census_tract", "spatial_type")