- Matplotlib 3.0 Cookbook
- Srinivasa Rao Poladi
- 375字
- 2025-04-04 16:06:37
How to do it...
The following code block draws five different plots to demonstrate most of the possible combinations for specifying the colors, line styles, and markers:
- Define the figure layout, as follows:
fig = plt.figure(figsize=(12,6))
- Define axes names for each of the plots:
ax1 = plt.subplot(321)
ax2 = plt.subplot(322)
ax3 = plt.subplot(323)
ax4 = plt.subplot(324)
ax5 = plt.subplot(325)
ax6 = plt.subplot(326)
- Set up data for x co-ordinates:
x = np.linspace(0, 10, 20)
- Following is the demonstration of many color specifications:
- xkcd:sky blue: Name from xkcd color survey
- green: CSS4 color name
- 1F1F1F1F: Hexadecimal value in RGBA format; digits range from 0-F
- b: CSS4 color abbreviation
- 1C0B2D: Hexadecimal value in RGB format
- pink: Tableau color
- C4: Color from property cycle; this is case-sensitive, and C has to be capitalized
We represent them in code format as follows:
color_list = ['xkcd:sky blue', 'green', '#1F1F1F1F', 'b', '#1C0B2D',
'pink', 'C4']
for i, color in enumerate(color_list):
y = x - (-5*i + 15)
ax1.plot(x, y, color)
ax1.set_title('colors demo')
- The following is a demonstration of the many line styles:
line_style = ['-', '--', '-.', ':', '.']
for i, ls in enumerate(line_style):
y = x - (-5*i + 15)
line, = ax2.plot(x, y, ls)
ax2.set_title('line style demo')
plt.setp(line, ls='steps')
- Here is a demonstration of the many marker specifications:
marker_list = ['.', ',', 'o', 'v', '^', 's', 'p', '*', 'h', 'H',
'D']
for i, marker in enumerate(marker_list):
y = x - (-5*i + 15)
ax3.plot(x, y, marker)
ax3.set_title('marker demo')
- The following is a demonstration of specifying combinations of color, line styles, and markers:
y = x # reset y to x
ax4.plot(x, y-10, 'k-d')
ax4.plot(x, y-5, 'c--')
ax4.plot(x, y, '|')
ax4.plot(x, y+5, '-.')
ax4.plot(x, y+10, color='purple', ls=':', marker='3')
ax4.plot(x, y+15, color='orange', linestyle=':', marker='1')
ax4.set_title('combination demo')
- The following is a demonstration of specifying colors and sizes of lines and markers:
ax5.plot(x, y-10, 'y-D', linewidth=2, markersize=4,
markerfacecolor='red',
markeredgecolor='k',markeredgewidth=1)
ax5.plot(x, y-5, 'm-s', lw=4, ms=6, markerfacecolor='red',
markeredgecolor='y', markeredgewidth=1)
ax5.set_title('Line and Marker Sizes Demo')
- The following is a demonstration of cap styles for dashed lines:
dash_capstyles = ['butt','projecting','round']
for i, cs in enumerate(dash_capstyles):
y = x - (-5*i + 15)
ax6.plot(x, y, ls='--', lw=10, dash_capstyle=cs)
ax6.set_title('dash capstyle demo')
- Use just the space in between the plots, and display the figure on the screen:
plt.tight_layout()
plt.show()