#
#
#
#
#
#
编辑 2013 年 10 月 14 日:
有关信息,现在已经为 python 实现了 ggplot(基于 matplotlib)。
查看此blog 或直接转至项目的github page 以获取更多信息和示例。
#
#
#
#
#
#
据我所知,matplotlib 中没有内置解决方案可以直接为您的图形提供与使用 R 制作的图形相似的外观。
一些包,比如mpltools,使用 Matplotlib 的 rc 参数添加了对样式表的支持,并且可以帮助您获得 ggplot 外观(参见ggplot style 的示例)。
但是,由于一切都可以在 matplotlib 中进行调整,因此您可能更容易直接开发自己的函数来实现您想要的功能。例如,下面是一个 sn-p,可让您轻松自定义任何 matplotlib 绘图的轴。
def customaxis(ax, c_left='k', c_bottom='k', c_right='none', c_top='none',
lw=3, size=20, pad=8):
for c_spine, spine in zip([c_left, c_bottom, c_right, c_top],
['left', 'bottom', 'right', 'top']):
if c_spine != 'none':
ax.spines[spine].set_color(c_spine)
ax.spines[spine].set_linewidth(lw)
else:
ax.spines[spine].set_color('none')
if (c_bottom == 'none') & (c_top == 'none'): # no bottom and no top
ax.xaxis.set_ticks_position('none')
elif (c_bottom != 'none') & (c_top != 'none'): # bottom and top
ax.tick_params(axis='x', direction='out', width=lw, length=7,
color=c_bottom, labelsize=size, pad=pad)
elif (c_bottom != 'none') & (c_top == 'none'): # bottom but not top
ax.xaxis.set_ticks_position('bottom')
ax.tick_params(axis='x', direction='out', width=lw, length=7,
color=c_bottom, labelsize=size, pad=pad)
elif (c_bottom == 'none') & (c_top != 'none'): # no bottom but top
ax.xaxis.set_ticks_position('top')
ax.tick_params(axis='x', direction='out', width=lw, length=7,
color=c_top, labelsize=size, pad=pad)
if (c_left == 'none') & (c_right == 'none'): # no left and no right
ax.yaxis.set_ticks_position('none')
elif (c_left != 'none') & (c_right != 'none'): # left and right
ax.tick_params(axis='y', direction='out', width=lw, length=7,
color=c_left, labelsize=size, pad=pad)
elif (c_left != 'none') & (c_right == 'none'): # left but not right
ax.yaxis.set_ticks_position('left')
ax.tick_params(axis='y', direction='out', width=lw, length=7,
color=c_left, labelsize=size, pad=pad)
elif (c_left == 'none') & (c_right != 'none'): # no left but right
ax.yaxis.set_ticks_position('right')
ax.tick_params(axis='y', direction='out', width=lw, length=7,
color=c_right, labelsize=size, pad=pad)
编辑:对于非接触式脊椎,请参阅下面的函数,该函数会导致脊椎位移 10 pts(取自 matplotlib 网站上的 this example)。
def adjust_spines(ax,spines):
for loc, spine in ax.spines.items():
if loc in spines:
spine.set_position(('outward',10)) # outward by 10 points
spine.set_smart_bounds(True)
else:
spine.set_color('none') # don't draw spine
例如,下面的代码和两张图向您展示了 matplotib 的默认输出(左侧),以及调用函数时的输出(右侧):
import numpy as np
import matplotlib.pyplot as plt
fig,(ax1,ax2) = plt.subplots(figsize=(8,5), ncols=2)
ax1.plot(np.random.rand(20), np.random.rand(20), 'ok')
ax2.plot(np.random.rand(20), np.random.rand(20), 'ok')
customaxis(ax2) # remove top and right spines, ticks out
adjust_spines(ax2, ['left', 'bottom']) # non touching spines
plt.show()
当然,您需要花费一些时间来确定必须在 matplotlib 中调整哪些参数以使您的图看起来与 R 的图完全一样,但我不确定现在还有其他选择。