Bahador Saket - 4 months ago 29

R Question

I am using following code to generate 10 bar charts side by side.

`library(reshape2)`

library(lattice)

data <- read.csv("/Users/.../data.csv", sep = ",")

df.long<-melt(data,id.vars=c("Vis","Task"))

df.long

barchart(Vis~value|Task,

groups=Vis,data=df.long,layout=c(5,2),

between = list(y=0.2),

auto.key = list(rectangles = TRUE, space = 'top', columns = 5),

origin = 0,

par.settings = list(fontsize=list(text=8) ),

box.ratio = 1/4,

box.width = 1

)

Here is my data in csv format.

`Vis,Accuracy,Task`

Bar chart,66,Anomalies

Line chart,52,Anomalies

Pie chart,80,Anomalies

Scatterplot,52,Anomalies

Table,66,Anomalies

Bar chart,100,Cluster

Line chart,33,Cluster

Pie chart,100,Cluster

Scatterplot,60,Cluster

Table,93,Cluster

Bar chart,90,Correlation

Line chart,30,Correlation

Pie chart,40,Correlation

Scatterplot,80,Correlation

Table,70,Correlation

Bar chart,73,Derived

Line chart,80,Derived

Pie chart,66,Derived

Scatterplot,86,Derived

Table,100,Derived

Bar chart,46,Distribution

Line chart,60,Distribution

Pie chart,60,Distribution

Scatterplot,73,Distribution

Table,46,Distribution

Bar chart,100,Extremum

Line chart,77.7,Extremum

Pie chart,94,Extremum

Scatterplot,61,Extremum

Table,88.8,Extremum

Bar chart,100,Filter

Line chart,75,Filter

Pie chart,100,Filter

Scatterplot,83,Filter

Table,83,Filter

Bar chart,75,Order

Line chart,66,Order

Pie chart,50,Order

Scatterplot,58,Order

Table,59,Order

Bar chart,40,Range

Line chart,66.6,Range

Pie chart,100,Range

Scatterplot,93,Range

Table,93,Range

Bar chart,91,Retrieve

Line chart,66,Retrieve

Pie chart,100,Retrieve

Scatterplot,75,Retrieve

Table,100,Retrieve

I generate the following visualization but the distance between bars is really high. How can I decrease the width?

Answer

The problem is that you are using `Vis`

both as the y variable and the grouping variable. This does not work very well in lattice. The easiest fix would probably just make a stacked barplot.

```
barchart(Vis~value|Task,
groups=Vis,
stack=T,
data=df.long,
layout=c(5,2),
auto.key = list(rectangles = TRUE, space = 'top', columns = 5),
origin = 0,
par.settings = list(fontsize=list(text=8) )
)
```

you could also remove Vis from the y-axis you are basically double labeling it the with color legend.

```
barchart(~value|Task,
groups=Vis,
data=df.long,
layout=c(5,2),
auto.key = list(rectangles = TRUE, space = 'top', columns = 5),
origin = 0,
par.settings = list(fontsize=list(text=8) )
)
```

This is kind of a weakness of the lattice plotting system. You can do something like this with ggplot a bit more easily

library(ggplot2)

```
ggplot(df.long, aes(Vis, value, fill=Vis)) +
geom_bar(stat='identity') +
coord_flip() + facet_wrap(~Task, ncol=5) +
theme(legend.position="top") +
scale_fill_discrete(name="")
```