我有以下代码:
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import numpy as np
np.random.seed(123456)
import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], columns=['x', 'y','z','w'])
f, axes = plt.subplots(1,4, figsize=(10,5))
for ax, col in zip(axes, df.columns):
df[col].plot(kind='pie', autopct='%.2f', ax=ax, title=col, fontsize=10)
ax.legend(loc=3)
plt.ylabel("")
plt.xlabel("")
plt.show()
如下图所示:
如何进行以下操作:
我认为,在这种情况下,手动绘制事物matplotlib
比使用pandas
数据框绘制方法容易。这样,您就可以控制更多。绘制所有饼图后,可以仅在第一个轴上添加图例:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
columns=['x', 'y','z','w'])
plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']
fig, axes = plt.subplots(1,4, figsize=(10,5))
for ax, col in zip(axes, df.columns):
ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
ax.set(ylabel='', title=col, aspect='equal')
axes[0].legend(bbox_to_anchor=(0, 0.5))
fig.savefig('your_file.png') # Or whichever format you'd like
plt.show()
pandas
绘图方法但是,如果您希望使用绘图方法:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
columns=['x', 'y','z','w'])
plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']
fig, axes = plt.subplots(1,4, figsize=(10,5))
for ax, col in zip(axes, df.columns):
df[col].plot(kind='pie', legend=False, ax=ax, autopct='%0.2f', title=col,
colors=colors)
ax.set(ylabel='', aspect='equal')
axes[0].legend(bbox_to_anchor=(0, 0.5))
fig.savefig('your_file.png')
plt.show()
两者产生相同的结果。
If you'd like to have a 2x2 or other grid arrangement of plots, plt.subplots
will return a 2D array of axes. Therefore, you'd need to iterate over axes.flat
instead of axes
directly.
For example:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
columns=['x', 'y','z','w'])
plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']
fig, axes = plt.subplots(nrows=2, ncols=2)
for ax, col in zip(axes.flat, df.columns):
ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
ax.set(ylabel='', title=col, aspect='equal')
axes[0, 0].legend(bbox_to_anchor=(0, 0.5))
fig.savefig('your_file.png') # Or whichever format you'd like
plt.show()
If you'd like a grid arrangement that has more axes than the amount of data you have, you'll need to hide any axes that you don't plot on. For example:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
columns=['x', 'y','z','w'])
plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']
fig, axes = plt.subplots(nrows=2, ncols=3)
for ax in axes.flat:
ax.axis('off')
for ax, col in zip(axes.flat, df.columns):
ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
ax.set(ylabel='', title=col, aspect='equal')
axes[0, 0].legend(bbox_to_anchor=(0, 0.5))
fig.savefig('your_file.png') # Or whichever format you'd like
plt.show()
If you don't want the labels around the outside, omit the labels
argument to pie
. However, when we do this, we'll need to build up the legend manually by passing in artists and labels for the artists. This is also a good time to demonstrate using fig.legend
to align the single legend relative to the figure. We'll place the legend in the center, in this case:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
columns=['x', 'y','z','w'])
plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']
fig, axes = plt.subplots(nrows=2, ncols=2)
for ax, col in zip(axes.flat, df.columns):
artists = ax.pie(df[col], autopct='%.2f', colors=colors)
ax.set(ylabel='', title=col, aspect='equal')
fig.legend(artists[0], df.index, loc='center')
plt.show()
类似地,百分比标签的径向位置由pctdistance
kwarg控制。大于1的值会将百分比标签移到饼图之外。但是,百分比标签(居中)的默认文本对齐方式假定它们位于饼图内部。一旦将它们移出饼图,我们将需要使用其他对齐约定。
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd
def align_labels(labels):
for text in labels:
x, y = text.get_position()
h_align = 'left' if x > 0 else 'right'
v_align = 'bottom' if y > 0 else 'top'
text.set(ha=h_align, va=v_align)
df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
columns=['x', 'y','z','w'])
plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']
fig, axes = plt.subplots(nrows=2, ncols=2)
for ax, col in zip(axes.flat, df.columns):
artists = ax.pie(df[col], autopct='%.2f', pctdistance=1.05, colors=colors)
ax.set(ylabel='', title=col, aspect='equal')
align_labels(artists[-1])
fig.legend(artists[0], df.index, loc='center')
plt.show()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句