Petr Razumov
Petr Razumov

Reputation: 2152

Recreate circular diagram with ggplot2

I'm trying to recreate the following illustration with R and ggplot2:

The Clean Architecture

I've created the following piece of code:

library(ggplot2)

df <- data.frame(names = c(
  "Enterprise Business Rules",
  "ApplicationBusiness Rules",
  "Interface Adapters",
  "Frameworks & Drivers"))

ggplot(df, aes(x = factor(1), fill = names)) +
  geom_bar(width = 1) +
  coord_polar() +
  xlab("") + ylab("") +
  theme_void() +
  theme(legend.title = element_blank())

But the output is incorrect:

ggplot2 output

I can't figure out how to change the order of layers. Maybe I'm missing something really important about ggplot2 and data.frames.

Upvotes: 2

Views: 171

Answers (2)

Bensstats
Bensstats

Reputation: 1056

Heres a crude solution:

Note the levels of df$names

> levels(df$names)
 [1] "ApplicationBusiness Rules" "Enterprise Business Rules"        
      "Frameworks & Drivers"      "Interface Adapters" 

What you need to do is redefine the levels of df$names

> df$names<-factor(df$names,rev(df$names))
> levels(df$names)
  [1] "Frameworks & Drivers"      "Interface Adapters" 
  "ApplicationBusiness Rules" "Enterprise Business Rules"

Now try your graph.

Upvotes: 2

dipetkov
dipetkov

Reputation: 3700

By default the names are ordered alphabetically. You can get around that by making names a factor and specifying the order with the levels argument. Separately, you can reverse the names ordering in the legend with the reverse = TRUE argument to the guide_legend function.

library(ggplot2)

names <- rev(c(
  "Enterprise Business Rules",
  "ApplicationBusiness Rules",
  "Interface Adapters",
  "Frameworks & Drivers"))
df <- data.frame(names = factor(names, levels = names))

ggplot(df, aes(x = factor(1), fill = names)) +
  geom_bar(width = 1) +
  coord_polar() +
  xlab("") + ylab("") +
  theme_void() +
  theme(legend.title = element_blank()) +
  guides(fill = guide_legend(reverse = TRUE))

Created on 2019-04-04 by the reprex package (v0.2.1)

Upvotes: 3

Related Questions