gpt4 book ai didi

r - 在图表中使用列作为构面

转载 作者:行者123 更新时间:2023-12-05 04:17:38 24 4
gpt4 key购买 nike

我有下面的 CSV 文件示例:

Time,Metric,JASK,ADI,IYW,NMNLK,AGWF,SDGYU,SDFWF,FFSDD,SDSF
2,HAUY,90,0,0,1,0.5,0.9,1,0,0.5
2,Z12IQ8,92.7605,0.758917751,0.40473,0.985702222,0.872985058,0.937119768,0.985702222,0.40473,0.872985058
2,9KAH,93.4582,0.804411769,0.45694,0.987653333,0.865519578,0.942423344,0.987653333,0.45694,0.865519578
2,P0IIDS,93.4284,0.757522078,0.50426,0.982064444,0.832763706,0.946890638,0.982064444,0.50426,0.832763654
2,SDGHG772,92.7298,0.740310258,0.42053,0.983605556,0.878374248,0.938563198,0.983605556,0.42053,0.878374248
2,RS,93.0309,0.816649558,0.39101,0.990231111,0.883847443,0.936039127,0.990231111,0.39101,0.883847443
2,IHSFH215,93.08156,0.775562283,0.435494,0.985851333,0.866698007,0.940207215,0.985851333,0.435494,0.866697996
4,HAUY,89.563,0,0,1,0.499887673,0.89563,1,0,0.499887673
4,Z12IQ8,92.6136,0.760067731,0.427134234,0.984285922,0.879761369,0.936484701,0.984285922,0.427134234,0.879761369

我想在 ggplot2 中将其绘制为垂直条,其中列 Metric 是 x 轴,其值是 y 轴;我希望每个 Metric 按名为 JASK 的列分组,... SDSF:

require(ggplot2)

sample <- read.csv("path/to/data.csv")

ggplot(sample, aes(Metric, JASK)) +
labs(
x="Metrics",
y="Value (%)"
) +
geom_bar(aes(fill = Metric), position="dodge", stat="identity") +
facet_grid(~ require(ggplot2)

sample <- read.csv("C:/Users/Troy/Dropbox/misc/data.csv")

ggplot(sample, aes(Metric, JASK)) +
labs(
x="Metrics",
y="Value (%)"
) +
geom_bar(aes(fill = Metric), position="dodge", stat="identity") +
facet_grid(~Metric)

到目前为止,我在 facet_grid() 中使用了 c(JASK,ADI,IYW,NMNLK,AGWF,SDGYU,SDFWF,FFSDD,SDSF) 并以一个错误:

Error in layout_base(data, cols, drop = drop) :
At least one layer must contain all variables used for facetting

使用 facet_grid(~JASK+ADI+IYW+NMNLK+AGWF+SDGYU+SDFWF+FFSDD+SDSF) 以灾难告终 (see here)。

我怎样才能得到一个图表:

  • x 轴是公制
  • y 轴是 Metric 的原始值
  • 每个都由变量JASKADIIYWNMNLK分面/分组AGWFSDGYUSDFWFFFSDDSDSF

最佳答案

您遇到的关键问题是 ggplot 需要长格式的数据。您可以使用 melt 将数据转换为长格式:

library(reshape2)
df.mlt <- melt(df, id.vars=c("Time", "Metric"))

您应该检查 df.mlt 以了解我所说的“长格式”是什么意思。使用长格式绘图的数据变得微不足道:

ggplot(df.mlt, aes(x=Metric, y=value, fill=as.factor(Time))) + 
geom_bar(stat="identity") +
facet_wrap(~ variable, scales="free_y") +
theme(axis.text.x=element_text(angle=90))

我不知道你想用 time 变量做什么,所以我只是用它来填充条形图。请注意,这仅绘制了您摘录的数据。

enter image description here

关于r - 在图表中使用列作为构面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21653269/

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