nev*_*int 7 python plot matplotlib
我有以下代码:
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()
Run Code Online (Sandbox Code Playgroud)
这使得以下情节:
我该如何做到以下几点:
在我看来,在这种情况下,手动绘制内容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()
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
两者产生相同的结果.
如果您想要2x2或其他网格排列的图形,plt.subplots将返回2D轴阵列.因此,您需要迭代axes.flat而不是axes直接迭代.
例如:
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()
Run Code Online (Sandbox Code Playgroud)
如果您希望网格排列的轴数多于您拥有的数据量,则需要隐藏任何未绘制的轴.例如:
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()
Run Code Online (Sandbox Code Playgroud)
如果您不希望外围的标签,请省略labels参数pie.但是,当我们这样做时,我们需要通过为艺术家传递艺术家和标签来手动建立图例.这也是展示使用fig.legend相对于图形对齐单个图例的好时机.我们将传奇放在中心,在这种情况下:
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()
Run Code Online (Sandbox Code Playgroud)
类似地,百分比标签的径向位置由pctdistancekwarg 控制.值大于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()
Run Code Online (Sandbox Code Playgroud)