gpt4 book ai didi

对角线以下的绘图值重新排序?

转载 作者:行者123 更新时间:2023-12-02 08:50:39 25 4
gpt4 key购买 nike

我有一个按行组织的数据文件,带有 x 标签、y 标签,然后是一个值。基本结构如下所示:

Factor_1,Factor_2,Number<br/>
apple,apple,1<br/>
banana,apple,1<br/>
apple,kiwi,6<br/>
apple,pear,1<br/>
watermelon,apple,8<br/>
banana,banana,3<br/>
banana,kiwi,2<br/>
banana,pear,1<br/>
banana,watermelon,9<br/>
kiwi,kiwi,9<br/>
pear,kiwi,4<br/>
kiwi,watermelon,4<br/>
pear,pear,3<br/>
pear,watermelon,9<br/>
watermelon,watermelon,1<br/>
...<br/>
...

使用此数据,我正在使用以下代码构建类似于相关矩阵的东西:

library(ggplot2)
library(reshape2)

d <- read.csv("my_file", head=TRUE, sep="\t")
x <- dcast(d, Factor_1~Factor_2)
x.m <- melt(x)
x.m <- ddply(x.m, .(variable))
(p <- ggplot(x.m, aes(variable, Factor_1)) + geom_tile(aes(fill = value), colour = "black") + scale_fill_gradient(low = "black", high = "green")

上面的代码给了我一个看起来像这样的情节:

plot

如何重新排序数据以构建具有以下格式的图表,其中所有数据都分组在对角线下方?

   A  B  K  P  W
W 1
P 3 9
K 9 4 4
B 3 2 1 9
A 1 1 6 1 8

最佳答案

我称它为“水果”:

fruit.tbl <- xtabs(V3 ~ V1+V2, data=fruits)
> melt(fruit.tbl)
V1 V2 value
1 apple apple 1
2 banana apple 0
3 kiwi apple 0
4 pear apple 0
5 watermelon apple 0
6 apple banana 1
7 banana banana 3
8 kiwi banana 0
9 pear banana 0
10 watermelon banana 0
11 apple kiwi 6
12 banana kiwi 2
13 kiwi kiwi 9
14 pear kiwi 0
15 watermelon kiwi 0
16 apple pear 1
17 banana pear 1
18 kiwi pear 4
19 pear pear 3
20 watermelon pear 0
21 apple watermelon 8
22 banana watermelon 9
23 kiwi watermelon 4
24 pear watermelon 9
25 watermelon watermelon 1

mfruit <- melt(fruit.tbl)
is.na(mfruit$value) <- mfruit$value==0

# Needed to swap x and y to get it the way you wanted
(p <- ggplot(melt(mfruit), aes(V2, V1,fill = value)) +
geom_tile( colour = "black") +
scale_fill_gradient(low = "black", high = "green")
)

enter image description here

关于对角线以下的绘图值重新排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8747397/

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