如何缩放饼图和条形图以同时显示

时间:2019-05-24 19:05:08

标签: python matplotlib

import matplotlib.pyplot as plt

x = [1,2,3,4,5]
y = [2,3,4,5,6]
z = [10, 9, 8, 7, 6]
a = [10, 12, 14, 3]
b = [1, 2, 3,4]
c = [1,2,3,4,5]


scatter = plt.scatter(x,y,marker="o", label="Label 1",color="r")
line = plt.plot(x,z,label="Label 2",color="g")
bar = plt.bar(a,b)
pie = plt.pie(c,labels=["Tom", "Dick", "Harry", "And", "Nervous"])
plt.title("Scatter and line")
plt.xlabel("X-label")
plt.ylabel("Y-label")
plt.legend()
plt.show()

上面的代码打印了我想要的所有内容,但是饼图与图形数据不对齐。有没有办法让MatPlotLib作为两个单独的并排图表打开它们,或者让它们在指定位置(例如x = 15,y = 15)将饼图覆盖在条形图上

我在下面提供了一个示例(图例有些偏离,因此请忽略它们) 我想要像第一行或第二行这样的输出。

谢谢

enter image description here

1 个答案:

答案 0 :(得分:2)

我相信matplotlib.pyplot.subplot可以并排绘制它们。

我对您的代码进行了一些重新排列,以适应这两个子图:

# create first subplot on the left (1 row, 2 columns, position 1)
plt.subplot(121)
pie = plt.pie(c,labels=["Tom", "Dick", "Harry", "And", "Nervous"])

# create second subplot on the right (1 row, 2 columns, position 2)
plt.subplot(122)
scatter = plt.scatter(x,y,marker="o", label="Label 1",color="r")
line = plt.plot(x,z,label="Label 2",color="g")
bar = plt.bar(a,b)
plt.title("Scatter and line")
plt.xlabel("X-label")
plt.ylabel("Y-label")

plt.legend()
plt.show()

结果: result

相关问题