2

I'm making a stacked bar chart with R.

# initialize a data frame
df_values_2012  <- data.frame(
   workvalue = character (  )
,  most     = numeric (  ) 
,  second   = numeric (  )
,  third    = numeric (  )
,  fourth   = numeric (  )
,  fifth    = numeric (  )
,  stringsAsFactors=FALSE
   )

df_values_2012 [1 , ] <-
c (  "value01" ,
 7L, 25L, 46L, 17L, 5L)


df_values_2012 [2 , ] <-
c (  "value02" ,
 15L,  29L, 21L, 21L, 14L)


df_values_2012 [3 , ] <-
c (  "value03" ,
27L, 8L, 7L,  12L, 46L )

df_values_2012 [4 , ] <-
c (  "value04" ,
 28L, 16L, 13L, 26L, 17L )

df_values_2012 [5 , ] <-
c (  "value05" ,
23L, 22L,  13L, 25L, 17L  )`

df_values_2012

  workvalue most second third fourth fifth
1   value01    7     25    46     17     5
2   value02   15     29    21     21    14
3   value03   27      8     7     12    46
4   value04   28     16    13     26    17
5   value05   23     22    13     25    17

You will note that -both- the rows and the columns add up to 100.

I've been making a graph of the results. However, I'm having trouble with the legend.


barplot ( as.matrix  (  df_values_2012 [ , 2:6 ] )
, col=c("blue", "green", "red", "yellow", "cyan")
 )

barplot ( as.matrix (  df_values_2012  [ , 2:6 ] )
, col=c("blue", "green", "red", "yellow", "cyan")
, legend.text = df_values_2012  [ , 1]
)

barplot ( as.matrix (  df_values_2012  [ , 2:6 ] )
, col=c("blue", "green", "red", "yellow", "cyan")
, legend.text = df_values_2012  [ , 1]
, args.legend = "topleft"
)

The legend is on top of the graph. It's hard to make out.

Is there a way to put the legend on the side? Perhaps, by using mosaicplot, or ggplot?

What I've tried so far has not been successful. And poking through the docs takes a long time.

Thanks a lot!

vrajs5
  • 4,066
  • 1
  • 27
  • 44
  • Hello thelatemail, Thanks for the tip of the other posting. Plot a legend outside of the plotting area in base graphics? Although, I tried a number of variations of the using negative inset values for legend. But, no luck in getting it to work. See the code below. Does anyone have an example that works with my data? Thanks a lot! barplot ( as.matrix (temp [ , 2:6 ] ) , col=c("blue", "green", "red", "yellow", "cyan") , legend("topright", inset=c(-0.2,0), legend=temp [ , 1] ) ) Error in width/2 : non-numeric argument to binary operator – user3720870 Jun 09 '14 at 04:52
  • New to stackoverflow. I could add lots of code in the initial posting. Why can't I add a number of variations and error messagses in the responses? – user3720870 Jun 09 '14 at 04:54
  • As well, I tried the code for "legend" from the other posting. Running the command, added the legend fine for the "plot" in the same example. But not when I tried adding it to my barplot. – user3720870 Jun 09 '14 at 05:01

0 Answers0