本篇詳細介紹matplotlib.pyplot繪圖方式中坐标軸(axis),刻度值(trick label),刻度(tricks),子圖示題(title),圖示題(suptitle),坐标軸标題(xlabel,ylabel),網格線(grid)等參數的詳細設定,不過相對于官網還隻是冰山一角。
目錄
1、詳細代碼
2、補充資料1:plt.gca()的所有屬性(400+種)
3、補充資料2:plt.gca().spines屬性(200+)
4、參考資料
1、詳細代碼
想看某個參數的作用,修改之後即可檢視效果。
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] =['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(dpi=150)
#整張圖figure的标題自定義設定
plt.suptitle('整張圖figure的标題:suptitle',#标題名稱
x=0.5,#x軸方向位置
y=0.98,#y軸方向位置
size=15, #大小
ha='center', #水準位置,相對于x,y,可選參數:{'center', 'left', right'}, default: 'center'
va='top',#垂直位置,相對不x,y,可選參數:{'top', 'center', 'bottom', 'baseline'}, default: 'top'
weight='bold',#字型粗細,以下參數可選
# '''weight{a numeric value in range 0-1000, 'ultralight', 'light',
#'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold',
#'demi', 'bold', 'heavy', 'extra bold', 'black'}'''
#其它可繼承自matplotlib.text的屬性
#标題也是一種text,故可使用text的屬性,是以這裡隻是展現了冰山一角
rotation=1,##标題旋轉,傳入旋轉度數,也可以傳入vertical', 'horizontal'
)
plt.subplot(1,1,1)#繪制一個子圖
#設定文本屬性字典
font_self = {'family':'Microsoft YaHei',#設定字型
'fontsize': 10,#标題大小
'fontweight' : 'bold',#标題粗細,預設plt.rcParams['axes.titleweight']
'color' : (.228,.21,.28),
#'verticalalignment': 'baseline',
# 'horizontalalignment': 'right'
}
#每個子圖示題自定義設定
plt.title('每個子圖axes的标題:title',
fontdict=font_self,
loc='left',#{'center', 'left', 'right'}
#下面兩個參數可以在前面字典中設定,也可以在這設定;存在時,loc指title在整個figure的位置,例如上面的left指與figure的最左邊對齊,而不是與axes最左邊對齊
#ha='center',#會影響loc的使用,可選參數:{'center', 'left', right'}, default: 'center'
#va='center'#會影響loc的使用,可選參數:{'top', 'center', 'bottom', 'baseline'}, default: 'top'
pad=7,#子圖示題與上坐标軸的距離,預設為6.0
#其它可繼承自matplotlib.text的屬性
rotation=360,#标題旋轉,傳入旋轉度數,也可以傳入vertical', 'horizontal'
)
#坐标軸的開啟與關閉操作
plt.gca().spines['top'].set_visible(False)#關閉上坐标軸
plt.gca().spines['bottom'].set_visible(True)#開啟x軸坐标軸
plt.gca().spines['left'].set_visible(True)#開啟y軸坐标軸
plt.gca().spines['right'].set_visible(False)#關閉右軸
##plt.gca()具有大量屬性,也可以對刻度值、刻度、刻度值範圍等操作,可自行實驗,這裡隻提到了冰山一角
plt.gca().spines['bottom'].set_color('black')#x軸(spines脊柱)顔色設定
plt.gca().spines['bottom'].set_linewidth(10)#x軸的粗細,下圖大黑玩意兒就是這裡的傑作
plt.gca().spines['bottom'].set_linestyle('--')#x軸的線性
#同樣這裡隻提到了軸spines屬性的冰山一角,也可自行實驗
#繪制網格線
plt.grid()
#坐标軸刻度(tick)與刻度值(tick label)操作
plt.tick_params(axis='x',#對那個方向(x方向:上下軸;y方向:左右軸)的坐标軸上的tick操作,可選參數{'x', 'y', 'both'}
which='both',#對主刻度還是次要刻度操作,可選參數為{'major', 'minor', 'both'}
colors='r',#刻度顔色
#以下四個參數控制上下左右四個軸的刻度的關閉和開啟
top='on',#上軸開啟了刻度值和軸之間的線
bottom='on',#x軸關閉了刻度值和軸之間的線
left='on',
right='on',
direction='out',#tick的方向,可選參數{'in', 'out', 'inout'}
length=10,#tick長度
width=2,#tick的寬度
pad=10,#tick與刻度值之間的距離
labelsize=10,#刻度值大小
labelcolor='#008856',#刻度值的顔色
zorder=0,
#以下四個參數控制上下左右四個軸的刻度值的關閉和開啟
labeltop='on',#上軸的刻度值也打開了此時
labelbottom='on',
labelleft='on',
labelright='off',
labelrotation=45,#刻度值與坐标軸旋轉一定角度
grid_color='pink',#網格線的顔色,網格線與軸刻度值對應,前提是plt.grid()開啟了
grid_alpha=1,#網格線透明度
grid_linewidth=10,#網格線寬度
grid_linestyle='-',#網格線線型,{'-', '--', '-.', ':', '',matplotlib.lines.Line2D中的都可以用
)
#plt.xticks([])#x軸刻度值trick的關閉
plt.xticks(np.arange(0, 2, step=0.2),list('abcdefghigk'),rotation=45)
#自定義刻度标簽值,刻度顯示為您想要的一切(日期,星期等等)
#設定刻度範圍
plt.xlim(0,2)#x坐标軸刻度值範圍
plt.ylim(0,2)#y坐标軸刻度值範圍
#plt.gca().set((xlim=[0, 2], ylim=[0, 2])#x軸y軸坐标軸範圍操作
#設定刻度值之間步長(間隔)
from matplotlib.pyplot import MultipleLocator
plt.gca().xaxis.set_major_locator(MultipleLocator(0.2))
plt.gca().xaxis.set_minor_locator(MultipleLocator(0.1))
#plt.minorticks_off()#是否每個刻度都要顯示出來
plt.xlabel('X軸标題',
labelpad=22,#x軸标題xlabel與坐标軸之間距離
fontdict=font_self,#設定xlabel的字型、大小、顔色、粗細
#類似于上面,可繼承自matplotlib.text的屬性
rotation=90
)
以上代碼結果
2、補充資料1:plt.gca()的所有屬性(400+種)
屬性(400+種)如下,感興趣可以慢慢玩:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_add_text', '_adjustable', '_agg_filter', '_alpha', '_anchor', '_animated', '_aspect', '_autoscaleXon', '_autoscaleYon', '_autotitlepos', '_axes', '_axes_class', '_axes_locator', '_axisbelow', '_clipon', '_clippath', '_connected', '_contains', '_convert_dx', '_current_image', '_facecolor', '_frameon', '_gci', '_gen_axes_patch', '_gen_axes_spines', '_get_axis_list', '_get_clipping_extent_bbox', '_get_lines', '_get_patches_for_fill', '_get_view', '_gid', '_gridOn', '_in_layout', '_init_axis', '_label', '_layoutbox', '_left_title', '_make_twin_axes', '_mouseover', '_mouseover_set', '_navigate', '_navigate_mode', '_oid', '_on_units_changed', '_originalPosition', '_parse_scatter_color_args', '_path_effects', '_pcolorargs', '_picker', '_position', '_poslayoutbox', '_process_unit_info', '_prop_order', '_propobservers', '_quiver_units', '_rasterization_zorder', '_rasterized', '_remove_legend', '_remove_method', '_right_title', '_sci', '_set_artist_props', '_set_gc_clip', '_set_lim_and_transforms', '_set_position', '_set_title_offset_trans', '_set_view', '_set_view_from_bbox', '_shared_x_axes', '_shared_y_axes', '_sharex', '_sharey', '_sketch', '_snap', '_stale', '_sticky_edges', '_subplotspec', '_tight', '_transform', '_transformSet', '_twinned_axes', '_update_image_limits', '_update_line_limits', '_update_patch_limits', '_update_title_position', '_update_transScale', '_url', '_use_sticky_edges', '_validate_converted_limits', '_visible', '_xaxis_transform', '_xcid', '_xmargin', '_yaxis_transform', '_ycid', '_ymargin', 'acorr', 'add_artist', 'add_callback', 'add_child_axes', 'add_collection', 'add_container', 'add_image', 'add_line', 'add_patch', 'add_table', 'aname', 'angle_spectrum', 'annotate', 'apply_aspect', 'arrow', 'artists', 'autoscale', 'autoscale_view', 'axes', 'axhline', 'axhspan', 'axis', 'axison', 'axvline', 'axvspan', 'bar', 'barbs', 'barh', 'bbox', 'boxplot', 'broken_barh', 'bxp', 'callbacks', 'can_pan', 'can_zoom', 'change_geometry', 'child_axes', 'cla', 'clabel', 'clear', 'clipbox', 'cohere', 'colNum', 'collections', 'containers', 'contains', 'contains_point', 'contour', 'contourf', 'convert_xunits', 'convert_yunits', 'csd', 'dataLim', 'drag_pan', 'draw', 'draw_artist', 'end_pan', 'errorbar', 'eventplot', 'eventson', 'figbox', 'figure', 'fill', 'fill_between', 'fill_betweenx', 'findobj', 'fmt_xdata', 'fmt_ydata', 'format_coord', 'format_cursor_data', 'format_xdata', 'format_ydata', 'get_adjustable', 'get_agg_filter', 'get_alpha', 'get_anchor', 'get_animated', 'get_aspect', 'get_autoscale_on', 'get_autoscalex_on', 'get_autoscaley_on', 'get_axes_locator', 'get_axisbelow', 'get_children', 'get_clip_box', 'get_clip_on', 'get_clip_path', 'get_contains', 'get_cursor_data', 'get_data_ratio', 'get_data_ratio_log', 'get_default_bbox_extra_artists', 'get_facecolor', 'get_fc', 'get_figure', 'get_frame_on', 'get_geometry', 'get_gid', 'get_gridspec', 'get_images', 'get_in_layout', 'get_label', 'get_legend', 'get_legend_handles_labels', 'get_lines', 'get_navigate', 'get_navigate_mode', 'get_path_effects', 'get_picker', 'get_position', 'get_rasterization_zorder', 'get_rasterized', 'get_renderer_cache', 'get_shared_x_axes', 'get_shared_y_axes', 'get_sketch_params', 'get_snap', 'get_subplotspec', 'get_tightbbox', 'get_title', 'get_transform', 'get_transformed_clip_path_and_affine', 'get_url', 'get_visible', 'get_window_extent', 'get_xaxis', 'get_xaxis_text1_transform', 'get_xaxis_text2_transform', 'get_xaxis_transform', 'get_xbound', 'get_xgridlines', 'get_xlabel', 'get_xlim', 'get_xmajorticklabels', 'get_xminorticklabels', 'get_xscale', 'get_xticklabels', 'get_xticklines', 'get_xticks', 'get_yaxis', 'get_yaxis_text1_transform', 'get_yaxis_text2_transform', 'get_yaxis_transform', 'get_ybound', 'get_ygridlines', 'get_ylabel', 'get_ylim', 'get_ymajorticklabels', 'get_yminorticklabels', 'get_yscale', 'get_yticklabels', 'get_yticklines', 'get_yticks', 'get_zorder', 'grid', 'has_data', 'have_units', 'hexbin', 'hist', 'hist2d', 'hlines', 'ignore_existing_data_limits', 'images', 'imshow', 'in_axes', 'indicate_inset', 'indicate_inset_zoom', 'inset_axes', 'invert_xaxis', 'invert_yaxis', 'is_first_col', 'is_first_row', 'is_last_col', 'is_last_row', 'is_transform_set', 'label_outer', 'legend', 'legend_', 'lines', 'locator_params', 'loglog', 'magnitude_spectrum', 'margins', 'matshow', 'minorticks_off', 'minorticks_on', 'mouseover', 'mouseover_set', 'name', 'numCols', 'numRows', 'patch', 'patches', 'pchanged', 'pcolor', 'pcolorfast', 'pcolormesh', 'phase_spectrum', 'pick', 'pickable', 'pie', 'plot', 'plot_date', 'properties', 'psd', 'quiver', 'quiverkey', 'redraw_in_frame', 'relim', 'remove', 'remove_callback', 'reset_position', 'rowNum', 'scatter', 'secondary_xaxis', 'secondary_yaxis', 'semilogx', 'semilogy', 'set', 'set_adjustable', 'set_agg_filter', 'set_alpha', 'set_anchor', 'set_animated', 'set_aspect', 'set_autoscale_on', 'set_autoscalex_on', 'set_autoscaley_on', 'set_axes_locator', 'set_axis_off', 'set_axis_on', 'set_axisbelow', 'set_clip_box', 'set_clip_on', 'set_clip_path', 'set_contains', 'set_facecolor', 'set_fc', 'set_figure', 'set_frame_on', 'set_gid', 'set_in_layout', 'set_label', 'set_navigate', 'set_navigate_mode', 'set_path_effects', 'set_picker', 'set_position', 'set_prop_cycle', 'set_rasterization_zorder', 'set_rasterized', 'set_sketch_params', 'set_snap', 'set_subplotspec', 'set_title', 'set_transform', 'set_url', 'set_visible', 'set_xbound', 'set_xlabel', 'set_xlim', 'set_xmargin', 'set_xscale', 'set_xticklabels', 'set_xticks', 'set_ybound', 'set_ylabel', 'set_ylim', 'set_ymargin', 'set_yscale', 'set_yticklabels', 'set_yticks', 'set_zorder', 'specgram', 'spines', 'spy', 'stackplot', 'stale', 'stale_callback', 'start_pan', 'stem', 'step', 'sticky_edges', 'streamplot', 'table', 'tables', 'text', 'texts', 'tick_params', 'ticklabel_format', 'title', 'titleOffsetTrans', 'transAxes', 'transData', 'transLimits', 'transScale', 'tricontour', 'tricontourf', 'tripcolor', 'triplot', 'twinx', 'twiny', 'update', 'update_datalim', 'update_datalim_bounds', 'update_from', 'update_params', 'use_sticky_edges', 'viewLim', 'violin', 'violinplot', 'vlines', 'xaxis', 'xaxis_date', 'xaxis_inverted', 'xcorr', 'yaxis', 'yaxis_date', 'yaxis_inverted', 'zorder']
3、補充資料2:plt.gca().spines屬性(200+)
屬性(200+),感興趣可以自己玩:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_adjust_location', '_agg_filter', '_alias_map', '_alpha', '_animated', '_antialiased', '_axes', '_bind_draw_path_function', '_bounds', '_calc_offset_transform', '_capstyle', '_clipon', '_clippath', '_contains', '_convert_xy_units', '_dashes', '_dashoffset', '_edge_default', '_edgecolor', '_ensure_position_is_set', '_facecolor', '_fill', '_get_clipping_extent_bbox', '_gid', '_hatch', '_hatch_color', '_in_layout', '_joinstyle', '_label', '_linestyle', '_linewidth', '_mouseover', '_oid', '_original_edgecolor', '_original_facecolor', '_patch_transform', '_patch_type', '_path', '_path_effects', '_picker', '_position', '_process_radius', '_prop_order', '_propobservers', '_rasterized', '_recompute_transform', '_remove_method', '_set_edgecolor', '_set_facecolor', '_set_gc_clip', '_sketch', '_smart_bounds', '_snap', '_spine_transform', '_stale', '_sticky_edges', '_transform', '_transformSet', '_url', '_us_dashes', '_visible', 'add_callback', 'aname', 'arc_spine', 'axes', 'axis', 'circular_spine', 'cla', 'clipbox', 'contains', 'contains_point', 'contains_points', 'convert_xunits', 'convert_yunits', 'draw', 'eventson', 'figure', 'fill', 'findobj', 'format_cursor_data', 'get_aa', 'get_agg_filter', 'get_alpha', 'get_animated', 'get_antialiased', 'get_bounds', 'get_capstyle', 'get_children', 'get_clip_box', 'get_clip_on', 'get_clip_path', 'get_contains', 'get_cursor_data', 'get_data_transform', 'get_ec', 'get_edgecolor', 'get_extents', 'get_facecolor', 'get_fc', 'get_figure', 'get_fill', 'get_gid', 'get_hatch', 'get_in_layout', 'get_joinstyle', 'get_label', 'get_linestyle', 'get_linewidth', 'get_ls', 'get_lw', 'get_patch_transform', 'get_path', 'get_path_effects', 'get_picker', 'get_position', 'get_rasterized', 'get_sketch_params', 'get_smart_bounds', 'get_snap', 'get_spine_transform', 'get_tightbbox', 'get_transform', 'get_transformed_clip_path_and_affine', 'get_url', 'get_verts', 'get_visible', 'get_window_extent', 'get_zorder', 'have_units', 'is_frame_like', 'is_transform_set', 'linear_spine', 'mouseover', 'pchanged', 'pick', 'pickable', 'properties', 'register_axis', 'remove', 'remove_callback', 'set', 'set_aa', 'set_agg_filter', 'set_alpha', 'set_animated', 'set_antialiased', 'set_bounds', 'set_capstyle', 'set_clip_box', 'set_clip_on', 'set_clip_path', 'set_color', 'set_contains', 'set_ec', 'set_edgecolor', 'set_facecolor', 'set_fc', 'set_figure', 'set_fill', 'set_gid', 'set_hatch', 'set_in_layout', 'set_joinstyle', 'set_label', 'set_linestyle', 'set_linewidth', 'set_ls', 'set_lw', 'set_patch_arc', 'set_patch_circle', 'set_patch_line', 'set_path_effects', 'set_picker', 'set_position', 'set_rasterized', 'set_sketch_params', 'set_smart_bounds', 'set_snap', 'set_transform', 'set_url', 'set_visible', 'set_zorder', 'spine_type', 'stale', 'stale_callback', 'sticky_edges', 'update', 'update_from', 'validCap', 'validJoin', 'zorder']