在python ggplot中访问轴或图 [英] Accessing axis or figure in python ggplot

查看:74
本文介绍了在python ggplot中访问轴或图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python ggplot很不错,但是仍然很新,我发现有必要回退传统的matplotlib技术来修改我的图.但是我不确定如何将一个轴实例传递给ggplot,或者从中获取一个实例.

python ggplot is great, but still new, and I find the need to fallback on traditional matplotlib techniques to modify my plots. But I'm not sure how to either pass an axis instance to ggplot, or get one back from it.

因此,假设我建立了一个这样的情节:

So let's say I build a plot like so:

import ggplot as gp

(明确导入)

p = gp.ggplot(gp.aes(x='basesalary', y='compensation'), data = df)
p + gp.geom_histogram(binwidth = 10000)      

到目前为止没有问题.但是,现在让我们说我想要对数刻度的y轴.我希望能够做到这一点:

No problems so far. But now let's say I want the y-axis in log scale. I'd like to be able to do this:

plt.gca().set_yscale('log')

很遗憾,plt.gca()无法访问ggplot创建的轴.我最后得到两个图:ggplot的直方图以线性比例表示,而空图以对数比例y轴表示.

Unfortunately, plt.gca() doesn't access the axis created by ggplot. I end up with two figures: the histogram from ggplot in linear scale, and an empty figure with a log-scale y axis.

我已经尝试了gca()gcf()的一些变体,但是没有成功.

I've tried a few variations with both gca() and gcf() without success.

推荐答案

自2013年提出此问题以来,可能已有一些更改.从ggplot生成matplotlib图形的方法是

There might have been some changes since 2013 when this question was asked. The way to produce a matplotlib figure from a ggplot is

g.make()

在那之后,图形和轴可以通过

after that, figure and axes can be obtained via

fig = plt.gcf()
ax = plt.gca()

,或者,如果还有更多轴,则为axes = fig.axes.

or, if there are more axes, axes = fig.axes.

然后,可以在matplotlib中添加其他功能,例如

Then, additional features can be added in matplotlib, like also shown in this question's answer.

最后,可以使用常用的savefig命令保存该图.

Finally the plot can be saved using the usual savefig command.

完整示例:

import ggplot as gp
import matplotlib.pyplot as plt

# produce ggplot
g = gp.ggplot(gp.aes(x='carat', y='price'), data=gp.diamonds)
g = g + gp.geom_point()
g = g + gp.ylab(' ')+ gp.xlab(' ')
# Make
g.make()

# obtain figure from ggplot
fig = plt.gcf()
ax = plt.gca()
# adjust some of the ggplot axes' parameters
ax.set_title("ggplot plot")
ax.set_xlabel("Some x label")
plt.savefig(__file__+".png")
plt.show()

这篇关于在python ggplot中访问轴或图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆