ggplot2 geom_bar fill aesthetic

2019-08-02 04:03发布

问题:

I have following code to graph a contracts in different countries.

Country <- CCOM$Principal.Place.of.Performance.Country.Name
Val <- CCOM$Action_Absolute_Value
split <- CCOM$Contract.Category

ggplot(CCOM, aes(x = Country, y = Val, fill = levels(split))) +
    geom_bar(stat = "identity")

I want a simple stacked bar chart with the bars colored by the contract category which is the variable "split" (ie. CCOM$Contract.Category).

However when I run the code it produces the graph below:

Why won't gplot separate the spending into three distinct blocks? Why do I get color sections scattered throughout the chart.? I have tried using factor(split) and levels(split) but does not seem to work. Maybe I am putting it in the wrong position.

回答1:

as you suggest order provides a solution:

ggplot(CCOM[order(CCOM$split), ], aes(x = Country, y = Val, fill = Contract.Category)) +
   geom_bar(stat = "identity")

I have a similar example where I use the equivalent of fill as Contact.Category and it still requires the reordering.



回答2:

Ah, I just realized what was going on. You seem scared to modify your data frame, don't be! Creating external vectors for ggplot is asking for trouble. Rather than create Country and Val as loose vectors, add them as columns to your data:

CCOM$Country <- CCOM$Principal.Place.of.Performance.Country.Name
CCOM$Val <- CCOM$Action_Absolute_Value

Then your plot is nice and straightforward, you don't have to worry about order or anything else.

ggplot(CCOM, aes(x = Country, y = Val, fill = Contract.Category)) +
    geom_bar(stat = "identity")


标签: r ggplot2