1

我使用 geom_tile 和 geom_text 创建了一个带有 ggplot 的图形。我希望能够从一列中读取数字并将它们全部排列。我将字体设置为 Courier 并使用 hjust 来证明数字的合理性(否则负号会偏离对齐方式)。但是,我无法找到一种方法来保持正确的对齐方式并将文本居中放置在每个框的中间。关于如何让数字对齐以便您可以快速扫描列的任何想法?

下面的可重现示例。

require(reshape2)
require(ggplot2)
require(scales)

set.seed(504)
df_graph <- data.frame("Category"=c("Green","Blue","Red","Yellow","Black","Random1","Random2","Random3","Random4","Random5","Random6","Random7",
                                    "Random8","Random9","Random10"),"Test1"=rnorm(15),"Test1"=rnorm(15),"Test2"=rnorm(15),"Test3"=rnorm(15),
                       "Test4"=rnorm(15),"Test5"=rnorm(15))

df_graph <- melt(df_graph)                       
df_graph$text <- round(df_graph$value, 2)

colors_used <- c("#B2182B","#D6604D","#F4A582","#FDDBC7","#F7F7F7","#D1E5F0","#92C5DE","#4393C3","#2166AC")
values <- seq(-4, 4, length = 9)

g <- ggplot(df_graph, aes(variable, Category))
g <- g + geom_tile(aes(fill = value), colour = "white", size=0.75)
g <- g + geom_text(aes(label=text),size=3, family="Courier", hjust = 1)
g <- g + scale_fill_gradientn(colours = colors_used, na.value = "#FFFFFF", values = values,rescaler = function(x, ...) x, oob = identity)
g <- g + theme_bw()
g <- g + theme(
  axis.text.x= element_text(color="black", size=10, angle = 45, hjust = 0.5),
  axis.text.y= element_text(color="black", size=8),
  axis.title.y = element_text(color="black",size=10),
  plot.title = element_text(color="black",size=14,face="bold"),
  legend.key = element_rect(fill="white"), legend.background = element_rect(fill=NA),
  legend.position="none",
  legend.title = element_blank(),
  panel.grid  = element_blank(),
  panel.border = element_blank()
)
4

1 回答 1

3

适当地使用hjust=0.5ingeom_text()并填充正数的标签,即预先添加空格字符以获得相等长度的标签:

df_graph$text <- format(round(df_graph$value, 2))

阴谋

于 2015-06-18T21:54:08.193 回答