Python中的ggplot样式
当我查看Pandas文档中的绘图风格时,发现那些图表看起来和默认的图表不一样。它们似乎模仿了ggplot的“外观和感觉”。
同样的情况也出现在seaborn这个包中。
我该如何加载这种风格呢?(即使我不使用笔记本也可以吗?)
5 个回答
我觉得joris的回答是更好的解决方案,因为你在使用Pandas。不过需要提到的是,Matplotlib可以通过输入命令matplotlib.style.use('ggplot')
来模仿ggplot的样式。
你可以在Matplotlib的画廊中查看一些示例。
Jan Katins的回答很好,但python-ggplot这个项目似乎已经不再活跃了。相比之下,plotnine这个项目发展得更好,提供了一种类似但表面上看起来不同的解决方案:
from plotnine import theme_bw
import matplotlib as mpl
theme = theme_bw()
with mpl.rc_context():
mpl.rcParams.update(theme.rcParams)
如果你想查看可用的样式:
import matplotlib.pyplot as plt
print(plt.style.available)
这段代码会显示出所有可用的样式。
你可以使用这个链接来选择你喜欢的样式:
https://tonysyu.github.io/raw_content/matplotlib-style-gallery/gallery.html
在python-ggplot中,你可以把主题应用到其他图表上:
from ggplot import theme_gray
theme = theme_gray()
with mpl.rc_context():
mpl.rcParams.update(theme.get_rcParams())
# plotting commands here
for ax in plt.gcf().axes:
theme.post_plot_callback(ax)
更新:如果你使用的 matplotlib 版本是 1.4 或更高版本,里面有一个新的 style
模块,默认就有一个 ggplot
风格。要启用这个风格,可以使用:
from matplotlib import pyplot as plt
plt.style.use('ggplot')
想查看所有可用的风格,可以检查 plt.style.available
。
同样,对于 seaborn 的样式设置,你可以这样做:
plt.style.use('seaborn-white')
或者,你也可以使用 seaborn
自己的工具来设置样式:
import seaborn as sns
sns.set()
set()
函数有更多选项,可以选择特定的样式(详细信息请查看 文档
)。需要注意的是,之前 seaborn
在导入时会自动做这些,但在最新版本(>= 0.8)中,这个功能已经不再自动执行了。
如果你还想在 Python 中使用类似 ggplot 的语法(不仅仅是样式),可以看看 plotnine
这个包,它在 Python 中实现了图形语法,语法和 R 的 ggplot2 非常相似。
注意:之前的回答提到要使用 pd.options.display.mpl_style = 'default'
。不过这个方法在 pandas 中已经被弃用了,现在推荐使用 matplotlib 的样式设置 plt.style(..)
,而且这个功能已经从 pandas 中移除了。