根据R和绘图中的范围制作堆积条形图

时间:2017-10-27 10:16:50

标签: r ggplot2 plotly ggplotly

我想在R中创建堆积条形图并使用虹膜数据集进行绘图。在x轴上,我想在代码中设置下面的iris_limits限制,y轴应该包含适合这些范围的所有Sepal.Length值。我想将值作为单个向量传递。此外,如果通过了解Sepal.Length的范围而不是硬编码可以使限制动态,请帮助。我写了一个带有值的基本脚本来给你一个想法。感谢。

library(plotly)
iris_limits <- c("1-4", "4-6", "6-8")
sepal <- c(2.4,5.4,7.1)
data <- data.frame(iris_limits, sepal)
p <- plot_ly(data, x = ~iris_limits, y = ~sepal, type = 'bar', name = 
'Sepal') %>%
layout(yaxis = list(title = 'Count'), barmode = 'group')
p

2 个答案:

答案 0 :(得分:2)

我尽力了解。首先将萼片长度划分为所需的类别iris_limits:“1-3”,“3-6”,“6-9”

iris$iris_limits <- cut(iris$Sepal.Length, c(1,3,6,9))

注意:没有萼片长度在1-3之间,所以你只有2组。

然后你想要每个萼片长度限制作为x轴上的一个单独的条形,并且每个单独的萼片长度属于相互叠加的类别?您链接到堆积条形图表,堆积条形图的颜色不同,这是您想要的吗?

为每个萼片长度创建一个ID:

iris$ID <- factor(1:nrow(iris))

绘图,如果您想要堆叠条形图的不同颜色,请设置color=~ID

library(plotly)
p <- plot_ly(iris, x = ~iris_limits, y = ~Sepal.Length, type = 'bar', color=~ID) %>%
  layout(yaxis = list(title = 'Count'), barmode = 'stack')

enter image description here

已编辑对于未堆叠但按iris_limits分组的版本,我切换到ggplot2以使用facet_wrap功能按{{1}隔离然后使用iris_limits

ggplotly

enter image description here

已编辑:Re:更改图例标题和工具提示显示

要更改图例标题,请使用gg <- ggplot(iris, aes(x=ID, y=Sepal.Length, fill=iris_limits)) + geom_bar(stat="identity", position="dodge") + facet_wrap(~iris_limits, scales="free_x", labeller=label_both) + theme_minimal() + xlab("") + ylab("Sepal Length") + theme(axis.text.x=element_blank()) ggplotly(gg) 。此处还需要更改labs下的legend.title字体大小以适应theme页边距。

要更改工具提示文字,请将ggplotly参数添加到text以创建所需的字符串,然后定义要aes aes中显示的tooltip值}。

ggplotly

答案 1 :(得分:0)

尝试使用cut

library(plotly)
iris$iris_limits <- as.numeric(cut(iris$Sepal.Length,3))
p <- plot_ly(iris, x = ~iris_limits, y = ~Sepal.Length, type = 'bar', name = 
               'Sepal') %>%
  layout(yaxis = list(title = 'Count'), barmode = 'group')
p

enter image description here

分组详情:

> iris$Sepal.Length[iris$iris_limits==1]
 [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.4 5.1 5.1 5.4 5.1 4.6 5.1 4.8 5.0 5.0 5.2 5.2 4.7 4.8
[29] 5.4 5.2 5.5 4.9 5.0 5.5 4.9 4.4 5.1 5.0 4.5 4.4 5.0 5.1 4.8 5.1 4.6 5.3 5.0 5.5 4.9 5.2 5.0 5.5 5.5 5.4 5.5 5.5
[57] 5.0 5.1 4.9
> iris$Sepal.Length[iris$iris_limits==2]
 [1] 5.8 5.7 5.7 6.4 6.5 5.7 6.3 6.6 5.9 6.0 6.1 5.6 6.7 5.6 5.8 6.2 5.6 5.9 6.1 6.3 6.1 6.4 6.6 6.7 6.0 5.7 5.8 6.0
[29] 6.0 6.7 6.3 5.6 6.1 5.8 5.6 5.7 5.7 6.2 5.7 6.3 5.8 6.3 6.5 6.7 6.5 6.4 5.7 5.8 6.4 6.5 6.0 5.6 6.3 6.7 6.2 6.1
[57] 6.4 6.4 6.3 6.1 6.3 6.4 6.0 6.7 5.8 6.7 6.7 6.3 6.5 6.2 5.9
> iris$Sepal.Length[iris$iris_limits==3]
 [1] 7.0 6.9 6.8 7.1 7.6 7.3 7.2 6.8 7.7 7.7 6.9 7.7 7.2 7.2 7.4 7.9 7.7 6.9 6.9 6.8
>