ggplot2 - barplot moving order

Question!

By default ggplot2 keeps the orders of variables constant in a plot, for example here: a will stay at the bottom, b in the middle, and c at the top.

enter image description here

What I would like to produce a graph where the order changes depending on the changing proportions (%).

So, time is on the x-axis and proportion (%) on the y-axis, like in a regular barplot.

You can visualise the table like this :

    code  color   `1`   `2`   `3`
1      a    red   0.2   0.8   0.2
2      b   blue   0.8   0.0   0.2
3      c yellow   0.0   0.2   0.6

What I would like is this:

enter image description here

The plot is ordered now according to the proportion. This enables to visualise more easily the hierarchy between the states over time. First blue (b) is more prominent, then red (a) and finally yellow (c). The order between the states in the plot can change.

However, I am not quite sure how to do it.

I tried using order: order(n) like :

td %>% group_by(time) %>% mutate(ord = order(n, decreasing = T)) 

and to explicitly provide the position to ggplot

but it doesn't seem to work.

t %>% 
  count(time, code) %>% group_by(time) %>% mutate(n = n / sum(n)) %>%
  ggplot(aes(time, n, fill = code)) + geom_bar(stat = 'identity') + 
  scale_fill_manual(values = c('red', 'blue', 'yellow')) + 
  scale_x_discrete(limits = factor(td$ord)) # positions # 

data

t = structure(list(id = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 
3L, 4L, 4L, 4L, 5L, 5L, 5L), .Label = c("1", "2", "3", "4", "5"
), class = "factor"), code = structure(c(2L, 1L, 1L, 2L, 3L, 
3L, 2L, 1L, 3L, 2L, 1L, 3L, 1L, 1L, 2L), .Label = c("a", "b", 
"c"), class = "factor"), time = structure(c(1L, 2L, 3L, 1L, 2L, 
3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("1", "2", 
"3"), class = "factor")), .Names = c("id", "code", "time"), row.names = c(NA, 
-15L), class = "data.frame")
By : giacomoV


Answers

You could simply order your data.frame according to column n, before calling ggplot():

t %>% 
  count(time, code) %>% group_by(time) %>% mutate(n = n / sum(n)) %>%
  arrange(desc(n)) %>% # only need to add this line
  ggplot(aes(time, n, fill = code)) + geom_bar(stat = 'identity') + 
  scale_fill_manual(values = c('red', 'blue', 'yellow')) 

enter image description here

By : mtoto


I would suggest the following general design pattern. It wastes an additional pointer, but will enforce the requirement that the const object will be able to only access const methods of the private object:

class ObjectImpl;

class const_Object {

public:

  const_Object(const ObjectImpl* object_impl)
    : _impl(object_impl);

  // Only const methods

private:      
  const ObjectImpl* _impl;
};

class Object : public const_Object
{
  Object(ObjectImpl* object_impl)
    : const_Object(object_impl), _impl(object_impl);

  // non-const methods go here.

private:      
  ObjectImpl* _impl;
};


Adding to Ian's answer, Any complex element that is named by root element will have factory method annotated with @XmlElementDecl().

You can resolve this, by moving the complex type declaration inline like below.

<xsd:schema xmlns= "http://www.foo.org/bar" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:annox="http://annox.dev.java.net" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    targetNamespace="http://www.foo.org/bar" jaxb:extensionBindingPrefixes="annox"
    jaxb:version="2.1" elementFormDefault="qualified">
    <xsd:element name="unit">
        <xsd:complexType>
            <xsd:annotation>
                <xsd:appinfo>
                    <annox:annotate>@javax.xml.bind.annotation.XmlRootElement(name="unit")
                    </annox:annotate>
                </xsd:appinfo>
            </xsd:annotation>
            <xsd:sequence>
                <xsd:any processContents="skip" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

ObjectFactory.class (no JAXBElement factory method generated here)

@XmlRegistry
public class ObjectFactory {


    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.foo.bar
     * 
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link Unit }
     * 
     */
    public Unit createUnit() {
        return new Unit();
    }

}

Test class:

@Test
public void testUnmarshalling() throws JAXBException, SAXException {
    JAXBContext context = JAXBContext.newInstance(Unit.class);

    Unmarshaller unmarshaller = context.createUnmarshaller();

    unmarshaller.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(new StreamSource(getClass().getClassLoader().getResourceAsStream("common.xsd"))));

    Object unit = unmarshaller.unmarshal(getClass().getResourceAsStream("unit.xml"));

    System.out.println(">>> Class is: " + unit.getClass().getName());

    StringWriter writer = new StringWriter();
    context.createMarshaller().marshal(unit, writer);

    System.out.println(">>> XML is: " + writer.toString());

    //assertTrue(unit instanceof Unit);
}

Test xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<unit xmlns="http://www.foo.org/bar">
    <text>Name</text>
</unit>

output :

>>> Class is: org.foo.bar.Unit
>>> XML is: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><unit xmlns="http://www.foo.org/bar"><text>Name</text></unit>
By : ulab


This video can help you solving your question :)
By: admin