簡體   English   中英

如何將莖葉圖輸出為圖

[英]How to output a stem and leaf plot as a plot

有沒有辦法將莖葉圖輸出到圖形設備,例如window() / quartz() 至少有兩種方法可以在 R 中獲取莖葉圖:圖形包中的?stem和 aplpack 包中的?stem.leaf 兩者都將文本輸出到控制台。 例如:

> set.seed(1)
> stem(rbinom(10, size=10, prob=.5))

  The decimal point is at the |

  3 | 0
  4 | 000
  5 | 0
  6 | 00
  7 | 000

如果這可以方便地輸出到圖形設備,在多圖形布局中它可以與其他繪圖(例如直方圖)組合,和/或保存為 png 文件,那就太好了。 我知道您可以輸出 LaTeX 並將其編譯為 pdf(例如,請參閱: Stem and Leaf from R into LaTeX ),但這不是很方便,也不是我真正想要的。 有沒有可以做到這一點的R函數? 有沒有簡單的手工編碼解決方案?

這是一個簡單的例子:

plot.new()
tmp <- capture.output(stem(iris$Petal.Length))
text( 0,1, paste(tmp, collapse='\n'), adj=c(0,1), family='mono' )

在此處輸入圖片說明

如果你想疊加一個直方圖,那么你可能想在tmp每個元素上使用text函數而不是paste ing。 strheightstrwidth這樣的函數對於查找坐標很有用。

gplots 和 plotrix 包中還有用於繪制文本和向繪圖添加表格的函數(其他包中的其他函數也可能沿着這些線存在)。

以下是等效的:

set.seed(1)
xx = rbinom(10, size=10, prob=.5)
barplot(t(table(xx)), horiz=T)

在此處輸入圖片說明

對於更相似的:

set.seed(1)
xx = rnorm(10)

xxch = as.character(xx)
ff = sapply(strsplit(xxch, '\\.'), function(x) x[1])
ss = sapply(strsplit(xxch, '\\.'), function(x) x[2])
first = sapply(strsplit(ss, ''), function(x) x[1])
second = sapply(strsplit(ss, ''), function(x) x[2])
third = sapply(strsplit(ss, ''), function(x) x[3])
dd = data.frame(ff, first, second, third)
dd = cbind(dd[1], sapply(dd[-1], as.numeric))
ddt = data.table(dd)
gg = ddt[order(ff,first)][,paste(first, collapse=""),by=ff]
gg$rr = rownames(gg)
ggplot(gg)+geom_text(aes(x=rr, y=1, label=paste(ff,'|',V1))) +
theme(axis.text = element_blank(),axis.title = element_blank(), axis.ticks=element_blank()) +
coord_flip()+ labs(title="Decimal is at |")

在此處輸入圖片說明

可能需要針對不同的集合調整代碼。

使用 capture.output(如@Greg 所建議)並使用 ggplot 繪圖:

tmp <- capture.output(stem(iris$Petal.Length))
stemdf = data.frame(tmp, rr=1:length(tmp))
ggplot(stemdf)+ geom_text(aes(x=rr, y=0, label=tmp), hjust=0) + 
    coord_flip()+ theme_classic() + 
    scale_x_discrete(breaks=NULL)+ 
    scale_y_discrete(breaks=NULL, limits=c(0,1))+ 
    theme(axis.text = element_blank(),
        axis.title = element_blank(), 
        axis.ticks=element_blank(), 
        panel.grid=element_blank(), 
        axis.line=element_blank())

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM