最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How do I scale a plot in matplotlib such that the tick marks are precisely 1 inch? - Stack Overflow

programmeradmin2浏览0评论

I am trying to make a graph where the plot outputs the correct scale as measured by the tick marks, not the overall figure size (which includes things like the margin around the graph).

How do I set the graph to be accurate as measured by the ticks? Preferably I would like one tick to be one inch.

Below is my code:

import numpy as np
import matplotlib.pyplot as plt

# Define the function you want to plot
**def my_function(x):
    return np.sin(x)+5

**# Define the number of inches per unit
**scale_factor = 1.0  # 1 unit = 1 inch

# Set figure size based on the scale (Ensure ticks match real inches)
x_range = 8  # How many units on the x-axis
y_range = 12  # How many units on the y-axis
fig_width = x_range * scale_factor  # Scale width to inches
fig_height = y_range * scale_factor  # Scale height to inches
dpi = 2400  # High DPI for accurate scaling

# Generate data
x = np.linspace(0, 2*np.pi, 10000)
y = my_function(x)

# Create the figure with correct physical dimensions
fig, ax = plt.subplots(figsize=(fig_width, fig_height), dpi=dpi)

ax.fill_between(x, y, 0, label="y = sin(x)+5", color='blue')

# Set tick intervals to match real inches
ax.set_xticks(np.arange(0, x_range + 1, 1))  # 1-inch spaced ticks
ax.set_yticks(np.arange(0, y_range+1, 1))  # Adjust as needed

# Set the major ticks to be 1 inch apart
ax.xaxis.set_major_locator(plt.MultipleLocator(1))
ax.yaxis.set_major_locator(plt.MultipleLocator(1))

# Save the figure
plt.savefig("scaled_tick_plot.svg", dpi=dpi, bbox_inches='tight')

# Show the plot
plt.show()

I am getting something close, but it seems like the x and y axes are scaling slightly differently. Are there any workarounds to this? I would like them to be exactly the same.

Note: If I upload this plot into a program like PowerPoint, I can see that the plot does not scale to the correct ratio, so I don't think it's a dpi issue.

发布评论

评论列表(0)

  1. 暂无评论