gpt4 book ai didi

r - 防止 plot_ly 重新排序矩阵

转载 作者:行者123 更新时间:2023-12-04 01:06:50 25 4
gpt4 key购买 nike

我最近更新了 R 和 Rstudio,自然而然地,我编写的大量脚本已损坏。

特别是导致我出现问题的一件事是下面的脚本。以前它用来输出一个热图,就像它出现在我给它制作矩阵的值的 csv 中一样。现在,后来的版本似乎改变了他们对事物的排序方式。它现在按数字升序对列及其标签进行排序,这使它们无序。如何防止它重新排列列,或指定它按照我提供的方式处理它们?

次要的美学问题并不是什么大问题。

这是代码:

library(ggplot2)
library(plotly)
library(RColorBrewer)
# Read in data
library(readr)


adjwallace <- read.csv() # see the link for the actual data http://pastebin.com/bBLs8uLt


rownames(adjwallace_recluster)[17] <- "Species" #Rename STree
names(adjwallace_recluster)[17] <- "Species"


# Preferences for xaxis
font.pref <- list(
size = 20,
family = "Arial, sans-serif",
color = "black"
)

x.axisSettings <- list(
title = "",
zeroline = FALSE,
showline = FALSE,
showticklabels = TRUE,
tickfont = font.pref,
showgrid = TRUE
)

# Preferences for yaxis
y.axisSettings <- list(
title = "",
zeroline = FALSE,
showline = FALSE,
showticklabels = TRUE,
tickfont = font.pref,
showgrid = TRUE
)

margins <- list(
l = 50,
r = 10,
b = 50,
t = 10,
pad = 1
)

# Plot graph as a heatmap
p <-plot_ly(z = ~data.matrix(adjwallace),
colors = "YlOrRd",
name = "Adjusted Wallace Coefficients",
x = names(adjwallace),
y = names(adjwallace),
colorbar = list(title = "Adjusted Wallace <br> Coefficient", titlefont = font.pref),
type = "heatmap") %>%
layout(xaxis=x.axisSettings,
yaxis=y.axisSettings,
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)',
margin = margins
)
p

以及此代码用于生成的图像(注意 x 和 y 轴排序):
enter image description here

脚本现在生成:
enter image description here

最佳答案

新旧热图中的值实际上相同;您的标签只是被重新排序。这是当前版本的 plotly 的奇怪行为(我会让其他人决定是否称其为“错误”)。轴标签按字母顺序重新排序。这是一个 MWE,清楚地显示了它:

dat <- matrix(c(1,2,3), nrow = 30, ncol = 30)
dimnames(dat) <- list(rownames(dat, FALSE, "r"),
colnames(dat, FALSE, "c"))
plot_ly(z=dat, x=colnames(dat), y = rownames(dat),
type = "heat map")

由于当前版本的 plotly 中的这种行为,我建议改用 ggplot2。事实上,您可以用更少的行数得出原始图,如下所示:
adjwallaceX <- melt(t(as.matrix(adjwallace)))
ggplot(data = adjwallaceX, aes(x = Var1, y = Var2)) +
geom_tile(aes(fill = value)) +
coord_equal() +
scale_fill_gradientn(colours = rev(brewer.pal(9,"YlOrRd"))) +
labs(fill='Adjusted Wallace Coefficient') +
theme(axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text.x=element_text(angle = 315, hjust = 0))

link to new plot

关于r - 防止 plot_ly 重新排序矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41231318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com