Issue
I've got an issue with matplotlib and the way it displays graphs.
In my Python Crash Course coursebook, one of early graphs is meant to display up to 1000 on the x axis, and up to 1,000,000 on the y axis. Instead it displays a float of up to 2.0, and 1e6 at the top.
I use VSCode. I worry I haven't properly configured it. When displaying the course materials made by the developer, I have the same problem.
Here's the graph I want.
Here's the graph I've got.
And here's my code.
import matplotlib.pyplot as plt
x_values = range(1, 1001)
y_values = [x**2 for x in x_values]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=10)
# Set chart title and label axes.
ax.set_title("Square Numbers", fontsize=24)
ax.set_xlabel("Value", fontsize=14)
ax.set_ylabel("Square of Value", fontsize=14)
# Set size of tick labels.
ax.tick_params(axis='both', which='major', labelsize=14)
# Set the range for each axis.
ax.axis([0, 1100, 0, 1100000])
plt.show()
If anyone has any experience with this, please let me know. I'm happy to change to another IDE that displays this properly, any recommendations would be welcome.
Solution
This is default matplotlib
behaviour. You can turn this off by creating a custom ScalarFormatter
object and turning scientific notation off. For more details, see the matplotlib documentation pages on tick formatters and on ScalarFormatter
.
# additional import statement at the top
import matplotlib.pyplot as plt
from matplotlib import ticker
# additional code before plt.show()
formatter = ticker.ScalarFormatter()
formatter.set_scientific(False)
ax.yaxis.set_major_formatter(formatter)
Note that, most likely, the axis label will be slightly cut off. One way to fix this is by adding fig.tight_layout()
before plt.show()
.
Answered By - luuk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.