r - 动态解析离散的 x 轴标签

标签 r parsing ggplot2

改编自这个已回答的问题:Customize axis labels 下面 MWE 中的这一行可以解析手动指定的 x 轴标签/值:

scale_x_discrete(labels=parse(text=c("The~First~Value","A~Second~Value","Finally~Third~Value")))

但是任何试图用 xo 动态替换 c() 的尝试(即包含导入表达式的有序列表)都失败了...

如何格式化或调整此列以使其正常工作?我很困惑,因为解析命令在 c()...

的内容上运行良好

在下面的模拟数据框中,为简单起见,我在此示例中包含的唯一字符是 ~(用于解析和产生空间)。完整上下文将包含从外部管理的表中导入的上标、下标、符号和希腊字符。

MWE:

library(ggplot2)

print("Program started")

z <- c("1","2","3")
x <- c("The~First~Value","A~Second~Value","Finally~Third~Value")
s <- c("No","No","No","Yes","Yes","Yes")
y <- c(1,2,3,2,3,4)
df <- as.data.frame(cbind(x=c(x,x),s=s,y=y,z=c(z,z)))

##########################################################################
xo <- as.data.frame(cbind(z,x))
xo <- xo[,"x"]
df[,"x"] <- factor(df[,"x"], levels=xo,ordered=TRUE)
##########################################################################
#xo <- levels(droplevels(xo))

gg <- ggplot(data = df, aes_string(x="x", y="y", weight="y", ymin=paste0("y"), ymax=paste0("y"), fill="s"));
dodge_str <- position_dodge(width = NULL, height = NULL);
gg <- gg + geom_bar(position=dodge_str, stat="identity", size=.3, colour = "black",width=.5)
#gg <- gg + scale_x_discrete(labels=parse(text=c("The~First~Value","A~Second~Value","Finally~Third~Value")))
gg <- gg + scale_x_discrete(labels=parse(text=c(xo)))

print(gg)

print("Program complete - a graph should be visible.")

最佳答案

class(xo) 调查让我意识到我正在尝试使用类型因子的对象,我认为它不能很好地作为参数处理 textparse 中。

与其尝试删除级别和因素,不如将其转换为字符列表(我一直认为它一直都是)一样简单且更稳定。

library(ggplot2)

print("Program started")

z <- c("1","2","3")
x <- c("The~First~Value","A~Second~Value","Finally~Third~Value")
s <- c("No","No","No","Yes","Yes","Yes")
y <- c(1,2,3,2,3,4)
df <- as.data.frame(cbind(x=c(x,x),s=s,y=y,z=c(z,z)))

##########################################################################
xo <- as.data.frame(cbind(z,x))
xo <- xo[,"x"]
df[,"x"] <- factor(df[,"x"], levels=xo,ordered=TRUE)
##########################################################################
xo <- as.character(xo)

gg <- ggplot(data = df, aes_string(x="x", y="y", weight="y", ymin=paste0("y"), ymax=paste0("y"), fill="s"));
dodge_str <- position_dodge(width = NULL, height = NULL);
gg <- gg + geom_bar(position=dodge_str, stat="identity", size=.3, colour = "black",width=.5)
#gg <- gg + scale_x_discrete(labels=parse(text=c("The~First~Value","A~Second~Value","Finally~Third~Value")))
#gg <- gg + scale_x_discrete(labels=parse(text=x))
gg <- gg + scale_x_discrete(labels=parse(text=xo))

print(gg)

print("Program complete - a graph should be visible.")

关于r - 动态解析离散的 x 轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29054282/

相关文章:

java - 输入字符串 999999999 的 NumberFormatException

R:ggplot2,如何注释面板图每个面板上的汇总统计数据

r - 有没有办法改变ggplot2中图例项之间的间距?

r - 用ggplot绘制水平线

r - 在 R 中查看数据表

parsing - 什么语法糖或语言特性使语言难以/难以解析?

r - 如何在 ggplot 的 geom_tile 中反转 Y 轴?

r - 如何使用 '|' 字符进行 strsplit,它的行为异常?

r - data.table 和 "by must evaluate to list"错误

PHP - 解析 HTML 字符串中的纯文本