首页 > 解决方案 > ggplot2 像另一个图形一样重新创建水平矩形

问题描述

我的目标是重新创建这个图表: 链接

我知道如何用 geom_text 绘制国旗和国家,但我不确定中间有文本的矩形(geom_rect() ?)。这是我创建的 df,但我不知道如何绘制。

df <- tibble(
  country = c('Argentina', 'Uruguay', 'Chile', 'Bolivia', 'Paraguay', 'Ecuador'),
  start = c(1976, 1973, 1973, 1971, 1954, 1972),
  end = c(1983, 1984, 1990, 1978, 1989, 1976),
  dictator = c('Juntas militares', 'Juntas militares', 'Pinochet', 'Hugo Banzer', 'Alfredo Stroessner', 'Guillermo Rodríguez Lara')
)

顺便说一句,这是我的第一个问题,所以任何关于如何改进的提示,将不胜感激

标签: rggplot2graphvisualization

解决方案


欢迎来到 stackOverflow。感谢您提供可重复的数据示例。

试试geom_segment几何。

library(ggplot2)

# Data
df <- tibble(
    country = c('Argentina', 'Uruguay', 'Chile', 'Bolivia', 'Paraguay', 'Ecuador'),
    start = c(1976, 1973, 1973, 1971, 1954, 1972),
    end = c(1983, 1984, 1990, 1978, 1989, 1976),
    dictator = c('Juntas militares', 'Juntas militares', 'Pinochet', 'Hugo Banzer', 'Alfredo Stroessner', 'Guillermo Rodríguez Lara')
)

    ggplot(data = df) +
    geom_segment(
        mapping = aes(x = start, xend = end, y = country, yend = country),
        size = 10,
        alpha = 0.5,
        color = "midnightblue"
    ) + 
    geom_text(aes(x = (start + end)/2, y = country, label = dictator)) +
    theme_minimal()

在此处输入图像描述


推荐阅读