I want to make a graph with matplotlib.

Asked 2 years ago, Updated 2 years ago, 74 views

Hello, I'm a beginner at python.
I have one question, how do I graph the output obtained by the for statement in matplotlib?
The graph I want to create is a scatterplot, and I want the は axis to be in the range of 1 to 10, and the Y axis to be in the for statement to be 0 to 5.
Source code created.

 from matplotlib import pyplot
For y in range (6):
    x = [1, 2, 3, 4, 5, 6]
    y1 = [y, y, y, y, y, y]
    pyplot.scatter(x,y1,c='b',label='test_data')
    pyplot.legend()
    pyplot.title('test')
    pyplot.show()

The above source code can be executed, but the result of the for statement set on the Y axis is
It is not reflected in the graph and it is all [0,0,0,0,0,0].
If you are familiar with python, please let me know.

python matplotlib

2022-09-30 19:20

2 Answers

Am I correct in understanding that you would like to draw 6x6 (36 points in total) on one graph?

If so, I think we can simply put pyplot.legend() or later out of loop.

 from matplotlib import pyplot
For y in range (6):
    x = [1, 2, 3, 4, 5, 6]
    y1 = [y, y, y, y, y, y]
    pyplot.scatter(x,y1,c='b',label='test_data')
pyplot.legend()
pyplot.title('test')
pyplot.show()


2022-09-30 19:20

The scatter part is the output part of the graph, so I think it's better to take it out of the for statement.
y ranges from 0 to 5 by adding repeated results to the list each time.
After creating an empty list (y1), add a value of y to the list in append.

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y1 = [ ]
For y in range (6):
    y1.append(y)
plt.scatter(x,y1,c='b',label='test_data')

plt.legend()
plt.title('test')
plt.show()

I've changed it to a more general way of writing on Matplotlib.
I hope it will be helpful.


2022-09-30 19:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.