如何填充 matplotlib 的网格?

6
我想呈现一个ggplot2样式的填充网格,就像这个图片所示:this
(来源:had.co.nz 我没有找到任何在线资源可以处理这种网格样式。我是否需要画出自己的矩形块来达成效果?
编辑:在尝试了Chris的解决方案后,我编写了一个脚本来帮助使matplotlib图表看起来像ggplot2,如果有人感兴趣的话,可以参考http://messymind.net/making-matplotlib-look-like-ggplot/

2
你的意思是填充背景颜色吗? - steffen
+1 鼓励您贡献解决方案。 - Chris
你熟悉 https://github.com/yhat/ggplot 吗? - tacaswell
@tcaswell 那个模块看起来对某些人来说是一个很好的选择。我个人认为 R/ggplot 语法不太好,更喜欢像往常一样使用 matplotlib。显然这是个人偏好。 - Bicubic
您可能还对style模块感兴趣,该模块位于主分支上(并将在1.4中推出),可更好地控制rcparams。 - tacaswell
2个回答

6
以下代码使用matplotlib.pyplot.grid打开网格并设置网格属性(线条颜色、风格和宽度),然后使用plt.gca().patch.set_facecolor('0.8')来更改坐标轴的颜色(我不确定是否有便捷函数可以实现此操作)。patch.set_facecolor的参数是任何matplotlib颜色
import numpy
import matplotlib.pyplot as plt

x = numpy.random.rand(10)
x = numpy.random.rand(10)

plt.plot(x, y, 'o')

plt.grid(True, color='w', linestyle='-', linewidth=2)
plt.gca().patch.set_facecolor('0.8')

plt.show()

结果是:

代码生成的图像


1
太棒了。我并没有期望会得到答案,更不用说是这么简单的一个了。我会进一步扩展它,并尝试将其放入画廊中。 - Bicubic

1

如果您只想为单个图表更新网格背景,可以执行以下操作:

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
ax.set_facecolor('#EBEBEB')
# Plot something..

但是,如果您想要为所有图表使用完整的ggplot样式,则Matplotlib带有一个ggplot主题,因此最简单的方法是启用该主题:

from matplotlib import pyplot as plt

plt.style.use('ggplot')

Seaborn 也有类似的主题:

import seaborn as sns

sns.set_style('darkgrid')

最后,如果您愿意,您也可以手动设置rcParams
from matplotlib import pyplot as plt
from matplotlib.ticker import AutoMinorLocator
import numpy as np

# This isn't a full styling but gets you most of the way.
ggplot_styles = {
    'axes.edgecolor': 'white',
    'axes.facecolor': 'EBEBEB',
    'axes.grid': True,
    'axes.grid.which': 'both',
    'axes.spines.left': False,
    'axes.spines.right': False,
    'axes.spines.top': False,
    'axes.spines.bottom': False,
    'font.size': 12,
    'grid.color': 'white',
    'grid.linewidth': '1.4',
    'xtick.color': '555555',
    'xtick.major.bottom': True,
    'xtick.minor.bottom': False,
    'ytick.color': '555555',
    'ytick.major.left': True,
    'ytick.minor.left': False,
}

plt.rcParams.update(ggplot_styles)

# Plot an example chart.
fig, ax = plt.subplots(figsize=(9, 6))
x = np.linspace(0, 14, 100)
for i in range(1, 7):
    ax.plot(x, np.sin(x + i * .5) * (7 - i))

# Set minor ticks/gridline cadence.
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))

# Turn minor gridlines on and make them thinner.
ax.grid(which='minor', linewidth=0.5)

matplotlib plot with ggplot style


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接