可变宽度条形图

chr*_*ris 16 plot r ggplot2

我想在R中生成一个区域/条形图,类似于: David MacKay的书 (David MacKay(优秀)"可持续能源"一书中的情节)

老实说,我甚至找不到像这样的情节的正确名称.它似乎是一个带有可变宽度条的条形图.确定性是一种强大的沟通工具.

csg*_*pie 26

您可以使用基本图形执行此操作.首先,我们指定一些宽度和高度:

widths = c(0.5, 0.5, 1/3,1/4,1/5, 3.5, 0.5)
heights = c(25, 10, 5,4.5,4,2,0.5)
Run Code Online (Sandbox Code Playgroud)

然后我们使用标准barplot命令,但是将块之间的空间指定为零:

##Also specify colours
barplot(heights, widths, space=0, 
        col = colours()[1:6])
Run Code Online (Sandbox Code Playgroud)

由于我们指定了宽度,我们需要指定轴标签:

axis(1, 0:6)
Run Code Online (Sandbox Code Playgroud)

要添加网格线,请使用以下grid函数:

##Look at ?grid to for more control over the grid lines
grid()
Run Code Online (Sandbox Code Playgroud)

并且您可以手动添加箭头和文本:

arrows(1, 10, 1.2, 12, code=1)
text(1.2, 13, "A country") 
Run Code Online (Sandbox Code Playgroud)

要在右上角添加方块,请使用以下polygon 函数:

polygon(c(4,4,5,5), c(20, 25, 25, 20), col="antiquewhite1")
text(4.3, 22.5, "Hi there", cex=0.6)
Run Code Online (Sandbox Code Playgroud)

这一切都给出了:

在此输入图像描述


旁白:在显示的图中,我使用par命令调整了几个方面:

par(mar=c(3,3,2,1), 
    mgp=c(2,0.4,0), tck=-.01,
    cex.axis=0.9, las=1)
Run Code Online (Sandbox Code Playgroud)


Eri*_*ail 18

灵感来自我上面提到的博客文章的代码,

df <- data.frame(x = c("Alpha", "Beta", "Gamma", "Delta"), width = c(25, 50, 75, 100), height = c(100, 75, 50, 25))
df$w <- cumsum(df$width)
df$wm <- df$w - df$width
df$wt <- with(df, wm + (w - wm)/2)

library(ggplot2)
p  <- ggplot(df, aes(ymin = 0))
p1 <- p + geom_rect(aes(xmin = wm, xmax = w, ymax = height, fill = x))
library(grid) # needed for arrow function
p1 + geom_text(aes(x = wt, y = height * 0.8, label = x)) + 
     theme_bw() + labs(x = NULL, y = NULL) + 
     theme(axis.ticks = element_blank(),axis.text.x = element_blank(), 
     axis.text.y = element_blank(), legend.position = "none") + 
     annotate("text", x = 120, y = 83, label = "a Beta block") + 
     geom_segment(aes(x = 100, y = 80, xend = 80, yend = 75), 
     arrow = arrow(length = unit(0.5, "cm")))
Run Code Online (Sandbox Code Playgroud)

β受体阻滞剂