简体   繁体   中英

ggplot2 geom_bar fill aesthetic

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.

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")

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM