GGPlot2 – how to create a plot

In previous posts, we learned how to manipulate data. Today, we will learn about the ggplot2 library to plot data in graphs. Let’s initialize the library:

Scatter plots

Let’s prepare the data for our first visualization. This will be a list of search coordinates in a square array where we found 1000 objects:

Using the ggplot library, we will plot their coordinates in a scatter plot using geom_point:

We have found several objects in several places, so they have the same coordinates. To display duplicate data, it is better to use geom_jitter, which changes the values slightly to allow “jittering” of the points:

The plot is more readable. There are other ggplot tools that can be used to plot overlapping data, but we leave it to you to find them.

To plot histograms, we use the geom_histogram function, where we can specify the width of the area (binwidth). Let’s look at where there were the most objects to the north:

Bar plots

Another type of commonly used chart is bar charts. Let’s prepare data that includes the names and distance people walked in four weeks:

We plot the distances from a single week on a chart using geom_bar:

We can use the color and fill attributes to change the appearance of the bars:

Xlab, ylab change the axis descriptions, and ggtitle adds a name to the chart:

We can quickly change the appearance of the chart by using default templates, e.g. theme_grey, theme_light:

In bar charts, we can group the data by name, for example. But first we need to reformat them using the gather tool from the tidyr library:

We can display the data in a bar plot:

At the top of the chart, the distances from the weeks are increasing, but if we change the postition attribute to “dodge” – the bars for each week are displayed side by side:

Axis descriptions and chart name are added or changed with labs:

We will change the position of the legend with theme:

Box plots

Finally, let’s make some boxplots with the new data. Let’s generate the distances run by 8 people in 30 days:

And let’s plot them in a boxplot:

Save plots to file

To save our charts to an external file (“eps”, “ps”, “tex”, “pdf”, “jpeg”, “tiff”, “png”, “bmp”, “svg” “wmf”) we use ggsave:

The function saves the last displayed plot by default. Saving a particular plot is done by assigning it to a variable and inserting it into the ggsave function:

The ggplot library has many functions and attributes that describe it. You can use all of these tools to create sophisticated plots. We leave the search for more complex solutions to you. You already have the basics.

Leave a Reply

Your email address will not be published.

Translate using Google Translate»
Social media & sharing icons powered by UltimatelySocial

Podoba Ci się nasza strona? Odwiedź nasz profil