[Python]常用画图函数
Posted stary_yan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Python]常用画图函数相关的知识,希望对你有一定的参考价值。
常用画图函数(Python)
Requirements
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Colors array
colors = ['lightcoral', 'teal', 'chartreuse', 'lightskyblue', 'mediumorchid', 'salmon', 'orangered',
'darkgreen', 'darkmagenta', 'cyan', 'tomato', 'goldenrod', 'mistyrose', 'peru', 'black', 'blue', 'lightblue',
'lavender', 'darkorange', 'yellowgreen', 'deepskyblue', 'forestgreen', 'green', 'seagreen', 'darkviolet',
'maroon', 'burlywood', 'lawngreen', 'springgreen', 'violet', 'mediumturquoise', 'lime', 'darkorchid',
'palegoldenrod', 'hotpink', 'skyblue', 'olive', 'gainsboro', 'floralwhite', 'cadetblue', 'azure',
'lightslategray', 'navajowhite', 'navy', 'thistle', 'coral', 'lavenderblush', 'seashell', 'aquamarine',
'khaki', 'sandybrown', 'aqua', 'midnightblue', 'lightsteelblue', 'moccasin', 'bisque', 'sienna', 'steelblue',
'darkseagreen', 'darksalmon', 'darkkhaki', 'lightsalmon', 'indianred', 'lightgreen', 'mediumslateblue',
'peachpuff', 'papayawhip', 'ivory', 'fuchsia', 'slateblue', 'beige', 'olivedrab', 'crimson', 'yellow',
'lightseagreen', 'deeppink', 'greenyellow', 'darkblue', 'magenta', 'mediumvioletred', 'blueviolet', 'tan',
'mediumaquamarine', 'darkgoldenrod', 'purple', 'snow', 'mediumblue', 'slategray', 'saddlebrown',
'lightgoldenrodyellow', 'darkred', 'turquoise', 'darkslateblue', 'darkslategray', 'darkcyan',
'blanchedalmond', 'ghostwhite', 'cornsilk', 'paleturquoise', 'lemonchiffon', 'linen', 'indigo', 'gold',
'palegreen', 'wheat', 'orchid', 'royalblue', 'cornflowerblue', 'darkturquoise', 'firebrick', 'silver',
'darkolivegreen', 'dodgerblue', 'chocolate', 'red', 'mintcream', 'white', 'plum', 'palevioletred',
'lightcyan', 'orange', 'rosybrown', 'lightpink', 'antiquewhite', 'lightgray', 'brown', 'gray', 'limegreen',
'dimgray', 'lightyellow', 'honeydew', 'aliceblue', 'mediumspringgreen', 'whitesmoke', 'mediumseagreen',
'oldlace', 'pink', 'powderblue', 'mediumpurple']
Plot Single Line
def plot_line(x=np.arange(10),
y=np.arange(10)):
"""
Plot a single line.
:param x: data array
:param y: label array
:return: None
"""
plt.figure()
plt.plot(x, y, 'bo', linestyle='-')
plt.title(''.format('Title'))
plt.xlabel(''.format('x label'), fontsize=14)
plt.ylabel(''.format('y label'), fontsize=10)
plt.show()
Plot Multi-lines
def plot_multi_lines(df=pd.DataFrame(index=['1', '2'],
data=[[1, 2], [3, 4]],
columns=['c1', 'c2'])):
"""
Plot multi lines in a figure.
:param df: DataFrame
:return: None
"""
plt.figure()
df.plot(figsize=(12, 8), title=''.format('Title'))
plt.show()
Plot barh
def plot_barh(records=np.array([1, 2]),
labels=np.array(['label-1', 'label-2'])):
"""
:param records: Data Array
:param labels: Label Array
:return: None
"""
plt.rcParams['axes.facecolor'] = 'white'
x = np.arange(len(records))
plt.subplots(figsize=(4, 2))
plt.barh(x, records, align="center", alpha=0.3, height=0.4)
plt.title(''.format('Title'))
plt.yticks(x, labels)
plt.ylim(-1, x[-1] + 1)
plt.xlabel(''.format('X label'))
plt.show()
Plot multi-barh
def plot_multi_barh(records=np.ones((4, 4)),
label=np.array(['label-'.format(x) for x in np.arange(4)]),
width=0.2,
alpha=0.7,
figsize=(20, 10),
xlim=1,
ylim=0.3):
"""
Plot Multi barh in a figure.
:param records: Data Matrix.
:param label: Label Array
:param width: the width of each bar.
:param alpha: Color alpha.
:param figsize: Figure size.
:param xlim:
:param ylim:
:return: None
"""
ind = np.arange(len(label))
fig, ax = plt.subplots(figsize=figsize)
ax_array = []
for i in range(records.shape[0]):
ax_array.append(ax.barh(ind + i * width, records[i], width, color=colors[i], alpha=alpha))
ax.set_yticks(ind + 2 * width)
ax.set_yticklabels(label)
plt.ylim(-1, len(ind) + ylim)
plt.xlim(0, np.max(records) + xlim)
ax.legend(([each[0] for each in ax_array]), label, loc='best')
plt.show()
Plot Stack Bar
def plot_stack_bar(records=np.ones(shape=(4, 5)),
legend_labels=np.array(['color-'.format(x) for x in np.arange(5)]),
index_label=np.array(['index-'.format(x) for x in np.arange(4)]),
width=0.4,
alpha=0.3,
ylabel='ylabel',
xlabel='xlabel',
title='title',
figsize=(24, 10),
normalize=False):
def norm_data(records):
for i in range(records.shape[0]):
total = np.sum(records[i][:])
for j in range(records.shape[1]):
records[i][j] /= total
if normalize:
norm_data(records)
fig = plt.figure(figsize=figsize, facecolor="white")
ax = fig.add_subplot(1, 1, 1)
ind = np.arange(records.shape[0])
axs_array = []
bottom_array = np.zeros(records.shape[0])
for i in range(records.shape[1]):
axs_array.append(ax.bar(ind,
records[:, i],
width=width,
color=colors[i],
bottom=bottom_array,
align='center',
alpha=alpha
))
bottom_array = bottom_array + records[:, i]
# for i in range(records.shape[0]):
# for j in range(records.shape[1]):
# plt.text(i, np.sum(records[i, 0: (j + 1)]),
# round(records[i][j], 2),
# ha="center")
plt.ylabel(''.format(ylabel), fontsize=20)
plt.title(''.format(title), fontsize=20)
plt.xlabel(''.format(xlabel), fontsize=20)
plt.xticks(ind, index_label, rotation=40)
plt.legend(([each[0] for each in axs_array]),
legend_labels,
loc='best')
plt.show()
Plot Pie
def plot_pie(data=np.ones(10),
labels=['index-'.format(x) for x in np.arange(10)]):
sizes = [360 * each / np.sum(data) for each in data]
plt.pie(sizes,
labels=labels,
autopct='%1.1f%%',
startangle=0,
colors=[each for each in colors[:data.shape[0]]])
plt.axis('equal')
plt.show()
以上是关于[Python]常用画图函数的主要内容,如果未能解决你的问题,请参考以下文章