%matplotlib inline
from ggplot import *
import pandas as pd
import numpy as np
ggplot allows you to adjust both the x and y axis to use a logarithmic scale. The scale_x_log
or scale_y_log
can be added to any plot. You can also adjust the type of logarithm that is used by providing a base
parameter (i.e. scale_x_log(base=2) for natural log
) to the function. If not specified log base 10 will be used.
diamonds.head()
ggplot(diamonds, aes(x='carat', y='price')) + geom_point()
ggplot(diamonds, aes(x='carat', y='price')) + \
geom_point() + \
scale_y_log()
df = pd.DataFrame(dict(
x=np.arange(1, 1000)
))
df['y'] = np.log(df.x)
df.head()
ggplot(df, aes(x='x', y='y')) + geom_point()
ggplot(df, aes(x='x', y='y')) + geom_point() + scale_x_log()
If you find yourself in the position where you need to reverse an axis, you can do so using scale_x_reverse
or scale_y_reverse
.
ggplot(mtcars, aes(x='mpg')) + geom_histogram() + scale_x_reverse()
ggplot(mtcars, aes(x='mpg')) + geom_histogram() + scale_y_reverse()
You can switch between different coordinate systems using the coord_*
family of layers. Just be careful that you're using the correct aesthetics! The available coordinate systems are:
coord_equal
coord_flip
coord_polar
coord_cartesian
(this is the default, so you never explicitly invoke it)coord_equal
¶coord_equal
will make the x and y axes use the same scale. This is handy if you're comparing 2 variables together, or want a square-looking plot.
ggplot(aes(x='beef', y='pork'), data=meat) + \
geom_point() + \
coord_equal()
ggplot(aes(x='beef', y='pork'), data=meat) + \
geom_point() + \
geom_abline(slope=1, intercept=0, color='teal') + \
coord_equal()
coord_flip
¶coord_flip
will make the x axis the y axis and vice-versa. So taking the plot we just made and flipping it would look like this.
# sadly, this doesn't appear to work
ggplot(aes(x='beef', y='pork'), data=meat) + \
geom_point() + \
coord_flip()
coord_polar
¶coord_polar
uses a polar coordinate system instead of cartesian.
df = pd.DataFrame({"x": np.arange(100)})
df['y'] = df.x * 10
df['z'] = ["a" if x%2==0 else "b" for x in df.x]
# polar coords
p = ggplot(df, aes(x='x', y='y')) + geom_point() + coord_polar()
print p
ggplot(df, aes(x='x', y='y')) + geom_point() + geom_line() + coord_polar()