r - 在 plotly (R) 中按另一列对条形图进行分组

标签 r plotly r-plotly

如何在 plotly 中使用 R 获得按州分组的条形图?

我想要的结果应该像这张用 excel 制作的示例图表:Click here for image

我的数据:

data <- data.frame(
  State = c(
    "Tennessee", "Tennessee", "Tennessee", "Tennessee",
    "Kentucky", "Kentucky", "Kentucky", "Kentucky", "Kentucky",
    "Georgia", "Georgia", "Georgia"
  ),
  City = c(
    "Chattanooga", "Knoxville", "Memphis", "Nashville",
    "Covington", "Owensboro", "Bowling Green", "Lexington", "Louisville",
    "Columbus City", "Augusta", "Atlanta City"
  ),
  Population = c(
    177571, 186239, 652717, 660388,
    40640, 57265, 58067, 295803, 597337,
    189885, 195844, 420033
  )
)

我的代码:

plot_ly(data) %>%
  add_trace(
    x = ~City,
    y = ~Population,
    type = 'bar',
    name = 'Population')

最佳答案

ggplot 中:

data <- data.frame(State, City, Population)
colnames(data)<-c("category","subcategory","population")

ggplot(data, aes(category, population)) +   
  geom_bar(aes(fill = category, color=subcategory), position = "dodge", stat="identity")+
  theme_minimal() +
  scale_color_manual(values=c(rep("white", 17))) +
  theme(legend.position="none") 

ggplot2 solution

并且,使用 ggplotly:

ggplotly()

enter image description here

关于r - 在 plotly (R) 中按另一列对条形图进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44289228/

相关文章:

javascript - 绘制一条垂直线来显示平均值

python - 密谋杀死我的 python 安装

r - 当 x 轴离散时,R 中的水平线

r - 为什么我的标签只是上下移动,而v只是左右移动?这不是很落后吗?

r - Shiny 的应用程序不更新隐藏的 slider

regex - 需要从字符串中的模式创建数据框

javascript - 使用 Plotly 定义饼图切片颜色

python - 如何用plotly绘制椭圆体

r - 使用 gganimate 动画 geom_bar 的问题

r - 加入数据但忽略缺失值