Search code examples
pythonmatplotlibcharts

2 similar graphs without rewriting the code


I want to compare 2 versions of the same graph with slight changes, is there a way of doing that without having to write the code twice?

here's a simple example, having to write the same code two times:

values = [1,2,3]
labels = ['test1','test2','test3']

plt.figure()
plt.pie(values,labels=labels,startangle= 15)
plt.figure()
plt.pie(values,labels=labels,startangle= 90)
plt.show()

Solution

  • I assume that you want to be able to look at two or maybe even more different angles using the same pie chart data. You can do this with a loop as shown below. If you just want 2 then you can just place two angles in the anglerange variable:

    values = [1,2,3]
    labels = ['test1','test2','test3']
    
    #This is a list of different angles you want to plot
    anglerange=list(range(0,180,30))
    print(anglerange)
    
    for i in anglerange:
        plt.pie(values,labels=labels,startangle= i)
        plt.figure()
    
    plt.show()
    
    

    enter image description here