python 中的 ggplot:绘图大小和颜色

ggplot in python: plot size and color

各位,

我正在尝试在 python 中使用 ggplot。

from ggplot import *
ggplot(diamonds, aes(x='price', fill='cut')) + geom_density(alpha=0.25) + facet_wrap("clarity")

我想做的几件事:

1) 我希望填充颜色和线条颜色,但如您所见,颜色全是灰色

2) 我正在尝试调整绘图的大小。在 R 中,我会在情节之前 运行 这个:

options(repr.plot.width=12, repr.plot.height=4)

但是,这在这里不起作用。

有谁知道我如何在分布中着色并更改绘图大小?

谢谢。附上电流输出。

颜色

使用color代替填充。 例如;

from ggplot import *
ggplot(diamonds, aes(x='price', color='cut')) + geom_density(alpha=0.25) + facet_wrap("clarity")

尺码

有几种方法可以做到这一点。

最简单的方法是 ggsave - 查看文档。

或者,使用 themeplot_margin 参数:

ggplot(...) ... + theme(plot_margin = dict(right = 12, top=8))

或者,使用 matplotlib 设置:

import matplotlib as mpl
mpl.rcParams["figure.figsize"] = "11, 8"
ggplot(...) + ...

希望对您有所帮助!

另一个解决方案,如果你不想改变 matplotlib 的配置:

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()

这是在搜索如何增加 plotnine 图的大小时 Google 中出现的最佳答案。 None 个答案对我有用,但增加 figure size 主题确实有效:

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))

使用最新的 ggplot2 Python: plotnine.

为了重塑情节大小,使用这个主题参数:figure_size(width, height)。宽度和高度以英寸为单位。

参考这个库文档:https://plotnine.readthedocs.io/en/stable/generated/plotnine.themes.themeable.figure_size.html#plotnine.themes.themeable.figure_size

参见以下示例:

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
)