我正在尝试制作甜甜圈图表.
唯一的问题是它们看起来像这样......
这是我的代码
ggplot(
diamonds,
aes(
x = cut,
fill = color
)
) +
geom_bar(
position = 'fill',
stat = 'bin'
) +
scale_y_continuous(
labels = percent_format()
) +
facet_grid(clarity ~ cut) +
coord_polar(theta = 'y')
Run Code Online (Sandbox Code Playgroud)
如何将我的图表从奇怪的馅饼变成宽度相同的圆圈?
这是一个很好的和整洁的方式:
library(ggplot2)
library(data.table)
# get data, calculate quantities of interest
diam <- diamonds; setDT(diam)
tabulated <- diam[, .N, by = .(cut, color, clarity)]
# plot
ggplot(tabulated, aes(x=2, y=N, fill=color)) +
geom_bar(position = 'fill', stat = 'identity') +
facet_grid(clarity ~ cut) +
xlim(0.5, 2.5) +
coord_polar(theta = 'y') +
labs(x=NULL, y=NULL)
Run Code Online (Sandbox Code Playgroud)
好的,这是如何工作的?让我们来看看你的代码 - 你得到一些看起来像甜甜圈但有不同孔尺寸的情节.这是为什么?"取消"数据并将输出视为条形是有帮助的.(为简单起见,我将仅分为两行.)
ggplot(subset(diamonds, as.numeric(clarity) <=2),
aes(x = cut, fill = color)) +
geom_bar(position = 'fill', stat = 'bin') +
facet_grid(clarity ~ cut)
Run Code Online (Sandbox Code Playgroud)
你有一个映射到X的值,它没有做任何有用的事情 - 它会偏移条形图,但由于你正在对该变量进行分面,每个图形中只有一个条形图.
然而,当您添加时coord_polar,具有偏移X值的图显示为甜甜圈,而具有x = 1的图显示为饼图因为具有coord_polar,所以堆叠条的系列彼此嵌套,并且X = 1表示最内层"线圈".
因此,解决方案首先将NOT实际值映射到X.您可以为所有绘图制作X = 1,但随后您将获得所有馅饼,而不是甜甜圈.你想要的是一个堆叠的条形,在x轴上有一些空间(这将是甜甜圈洞).你可以通过复制数据来做到这一点,所以你有两组堆叠条,然后消隐第一个堆栈.这是我以前的答案,它的确有效(详见编辑历史记录).
Hadley建议通过Twitter提出一个更简单的解决方案,我觉得有必要为后代发布:调整x限制以强制x轴上的一些前导空格.
首先,计算你想要的值(我正在使用data.table它):
library(data.table)
diam <- diamonds; setDT(diam)
tabulated <- diam[, .N, by = .(cut, color, clarity)]
Run Code Online (Sandbox Code Playgroud)
现在情节,在一堆酒吧之前有一些房间
有你想要的堆积条形图,你所要做的就是添加coord_polar(如帖子顶部所做).您可以使用x限制来根据自己的喜好调整甜甜圈/洞的比例.