如何使用带有 ggplot 的周期性 table 显示计数?

How to display counts using the periodic table with ggplot?

我有一个元素成分列表,我想显示元素包含在映射到周期性 table 的成分中的次数(例如 CH4HC 的计数增加一)。

如何使用 ggplot 执行此操作?有我可以使用的地图吗?

通过一些搜索,我在 this example code project. They had an Access Database with element information. I've exported it to this gist 中找到了有关周期性 table 的信息。您可以使用 httr 库和

导入数据
library(httr)
dd <- read.table(text=content(GET("https://gist.githubusercontent.com/MrFlick/c1183c911bc5398105d4/raw/715868fba2d0d17a61a8081de17c468bbc525ab1/elements.txt")), sep=",", header=TRUE)

(您可能应该创建自己的本地版本以便将来更容易加载。)

那么您的另一个挑战是将 "CH4" 之类的东西分解为原始元素计数。我已经创建了这个辅助函数,我认为它可以满足您的需要。

decompose <- function(x) {
    m <- gregexpr("([A-Z][a-z]?)(\d*)", x, perl=T)
    dx <- Map(function(x, y) {
        ElementSymbol <- gsub("\d","", x)
        cnt <- as.numeric(gsub("\D","", x))
        cnt[is.na(cnt)]<-1
        cbind(Sym=y, as.data.frame(xtabs(cnt~ElementSymbol)))
    }, regmatches(x,m), x)
    do.call(rbind, dx)
}

这里我测试功能

test_input <- c("H2O","CH4")
decompose(test_input)

#   Sym ElementSymbol Freq
# 1 H2O             H    2
# 2 H2O             O    1
# 3 CH4             C    1
# 4 CH4             H    4

现在我们可以结合数据和参考信息来作图了

library(ggplot2)
ggplot(merge(decompose("CH4"), dd), aes(Column, -Row)) + 
    geom_tile(data=dd, aes(fill=GroupName), color="black") + 
    geom_text(aes(label=Freq))

显然有改进的机会,但这应该给你一个好的开始。

您可能需要更强大的分解函数。看起来 CHNOSZ 包有一个

library(CHNOSZ)
data(thermo)
decompose <- function(x) {
    do.call(`rbind`, lapply(x, function (x) {
       z <- makeup(x)
       cbind(data.frame(ElementSymbol = names(z),Freq=z), Sym=x)
    }))
}
ggplot(merge(decompose("CaAl2Si2O7(OH)2*H2O"), dd), aes(Column, -Row)) + 
    geom_tile(data=dd, aes(fill=GroupName), color="black") + 
    geom_text(aes(label=Freq))