Reputation: 3580
Folks,
I'm trying to use ggplot in python.
from ggplot import *
ggplot(diamonds, aes(x='price', fill='cut')) + geom_density(alpha=0.25) + facet_wrap("clarity")
Couple things I am trying to do:
1) I expected the color to be both filled and for the lines, but as you can see the color is all grey
2) I am trying to adjust the size of the plot. In R I would run this before the plot:
options(repr.plot.width=12, repr.plot.height=4)
However, that doesn't work here.
Does anyone know how I color in the distribution and also change the plot size?
Thank you. The current output is attached.
Upvotes: 13
Views: 19486
Reputation: 709
Use the most recent ggplot2 for Python: plotnine.
In order to reshape the plot size, use this theme parameter: figure_size(width, height). Width and height are in inches.
Refer to this library documentation: https://plotnine.readthedocs.io/en/stable/generated/plotnine.themes.themeable.figure_size.html#plotnine.themes.themeable.figure_size
See the following example:
from plotnine import *
(ggplot(df)
+ aes(x='column_X', y='column_Y', color = 'column_for_collor')
+ geom_line()
+ theme(axis_text_x = element_text(angle = 45, hjust = 1))
+ facet_wrap('~column_to_facet', ncol = 3) # ncol to define 3 facets per line
+ theme(figure_size=(16, 8)) # here you define the plot size
)
Upvotes: 28
Reputation: 3062
This is the top answer that comes up in Google when searching how to increase the size of plotnine
plot. None of the answers worked for me but increasing the figure size theme did:
from plotnine import *
from plotnine.data import diamonds
ggplot(diamonds, aes(x='price', color='cut')) + geom_density(alpha=0.25) + facet_wrap("clarity") + theme(figure_size = (10, 10))
Upvotes: 3
Reputation: 21
Another solution, if you don't want to alter matplotlib's configuration:
from ggplot import *
from matplotlib import pyplot as plt
p = (ggplot(diamonds,
aes(x='x', y='y', color='cut', fill='cut')) +
geom_point() +
facet_wrap(x='cut'))
# This command "renders" the figure and creates the attribute `fig` on the p object
p.make()
# Then you can alter its properties
p.fig.set_size_inches(15, 5, forward=True)
p.fig.set_dpi(100)
p.fig
# And display the final figure
plt.show()
Upvotes: 2
Reputation: 6805
Color
Use color
instead of fill.
e.g.;
from ggplot import *
ggplot(diamonds, aes(x='price', color='cut')) + geom_density(alpha=0.25) + facet_wrap("clarity")
Size
A couple of ways to do this.
Easiest is with ggsave
- look up the documentation.
Alternatively, use theme
with plot_margin
argument:
ggplot(...) ... + theme(plot_margin = dict(right = 12, top=8))
Or, use matplotlib settings:
import matplotlib as mpl
mpl.rcParams["figure.figsize"] = "11, 8"
ggplot(...) + ...
Hope that helped!
Upvotes: 0