[R] Way to Plot Multiple Variables and Change Color

G.Maubach at weinwolf.de G.Maubach at weinwolf.de
Tue Mar 28 15:05:12 CEST 2017


Hi All,

in my current project I have to plot a whole bunch of related variables 
(item batteries, e.g. How do you rate ... a) Accelaration, b) Horse Power, 
c) Color Palette, etc.) which are all rated on a scale from 1 .. 4.

I need to present the results as stacked bar charts where the variables 
are columns and the percentages of the scales values (1 .. 4) are the 
chunks of the stacked bar for each variable. To do this I have transformed 
my data from wide to long and calculated the percentage for each variable 
and value. The code for this is as follows:

-- cut --

dfr <- structure(
  list(
    v07_01 = c(3, 1, 1, 4, 3, 4, 4, 1, 3, 2, 2, 3,
               4, 4, 4, 1, 1, 3, 3, 4),
    v07_02 = c(1, 2, 1, 1, 2, 1, 4, 1, 1,
               4, 4, 1, 4, 4, 1, 3, 2, 3, 3, 1),
    v07_03 = c(3, 2, 2, 1, 4, 1,
               2, 3, 3, 1, 4, 2, 3, 1, 4, 1, 4, 2, 2, 3),
    v07_04 = c(3, 1, 1,
               4, 2, 4, 4, 2, 2, 2, 4, 1, 2, 1, 3, 1, 2, 4, 1, 4),
    v07_05 = c(1,
               2, 2, 2, 4, 4, 1, 1, 4, 4, 2, 1, 2, 1, 4, 1, 2, 4, 1, 4),
    v07_06 = c(1,
               2, 1, 2, 1, 1, 3, 4, 3, 2, 2, 3, 3, 2, 4, 2, 3, 1, 4, 3),
    v07_07 = c(3,
               2, 3, 3, 1, 1, 3, 3, 4, 4, 1, 3, 1, 3, 2, 4, 1, 2, 3, 4),
    v07_08 = c(3,
               2, 1, 2, 2, 2, 3, 3, 4, 4, 1, 1, 1, 2, 3, 1, 4, 2, 2, 4),
    cased_id = structure(
      1:20,
      .Label = c(
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "10",
        "11",
        "12",
        "13",
        "14",
        "15",
        "16",
        "17",
        "18",
        "19",
        "20"
      ),
      class = "factor"
    )
  ),
  .Names = c(
    "v07_01",
    "v07_02",
    "v07_03",
    "v07_04",
    "v07_05",
    "v07_06",
    "v07_07",
    "v07_08",
    "cased_id"
  ),
  row.names = c(NA, -20L),
  class = c("tbl_df", "tbl",
            "data.frame")
)

mdf <- melt(df)
d_result <- mdf  %>%
  dplyr::group_by(variable) %>%
  count(value)

ggplot(
  d_result,
  aes(variable, y = n, fill = value)) +
  geom_bar(stat = "identity") +
  coord_cartesian(ylim = c(0,100))

-- cut --

Is there an easier way of doing this, i. e. a way without need to 
transform the data?

How can I change the colors for the data points 1 .. 4?

I tried

-- cut --

  d_result,
  aes(variable, y = n, fill = value)) +
  geom_bar(stat = "identity") +
  coord_cartesian(ylim = c(0,100)) +
  scale_fill_manual(values = RColorBrewer::brewer.pal(4, "Blues"))

-- cut -

but this does not work cause I am mixing continuous and descrete values.

How can I change the colors for the bars?

Kind regards

Georg



More information about the R-help mailing list