我已經使用geom_tile和geom_text創建了ggplot圖。我希望能夠讀取一列中的數字並將它們全部列出。我將字體設置爲Courier,然後使用hjust來證明數字的正確性(否則負號會拋出對齊)。然而,我無法找到一種方法來保持這個正確的理由,並將文本置於每個框中間。關於如何讓數字排列起來以便您可以快速掃描列的任何想法?對齊文本右對齊,但在geom_text中的每個框的中心
下面是可重複使用的示例。
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()
)
添加標籤('label = format(text)')? – aosmith
我遇到的問題是當表中有NAs時,格式將使它們停留在表上,並且NAs/0不會消失。 –
也許更新您的示例以包含NA,以便它再現您的真實情況?我無法想象如何通過「文本」中的缺失值(基於「值」)來「填充」值。格式化後,您可以簡單地用空格替換丟失的「文本」(因此需要在@rcs答案中在圖的外部格式化) - df_graph $ text [df_graph $ text ==「NA」] =「」' – aosmith