簡體   English   中英

如何填充 matplotlib 網格?

[英]How can I fill a matplotlib grid?

我想渲染一個 ggplot2 樣式的填充網格,a la 這個
(來源: had.co.nz

我一直無法找到以這種方式處理網格樣式的任何在線資源。 我是否必須求助於繪制我自己的矩形補丁之類的東西?

編輯:在嘗試 Chris 的解決方案后,如果有人感興趣,我編寫了一個腳本來幫助使 matplotlib 圖形看起來像 ggplot2。

http://messymind.net/making-matplotlib-look-like-ggplot/

以下代碼使用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()

結果是

上面代碼生成的圖

如果您只想更新單個圖表的網格背景,您可以這樣做:

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)

具有 ggplot 樣式的 matplotlib 圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM