Last active
March 10, 2020 05:34
-
-
Save dhermes/7ef47c5d660802bb911075e33738a138 to your computer and use it in GitHub Desktop.
Square grid for Pi day with `matplotlib`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# $ FILL_BETWEEN=true python grid.py | |
# Saved grid.pdf | |
# $ python grid.py | |
# Saved grid-no-fill.pdf | |
import os | |
import matplotlib.pyplot as plt | |
FILL_BETWEEN = "FILL_BETWEEN" in os.environ | |
def main(): | |
figure = plt.figure(figsize=(8.5, 11.0)) | |
ax = figure.gca() | |
ax.axis("off") | |
ax.grid(False) | |
column_width = 3 | |
max_column = 10 | |
row_width = 2 | |
max_row = 20 | |
digits = [0, 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 0, 0] | |
columns = list(range(max_column + 1)) | |
rows = list(range(max_row + 1)) | |
for column in columns: | |
ax.plot( | |
[column * column_width, column * column_width], | |
[0.0, max_row * row_width], | |
color="black", | |
) | |
for row in rows: | |
ax.plot( | |
[0.0, max_column * column_width], | |
[row * row_width, row * row_width], | |
color="black", | |
) | |
digit = digits[row] | |
if digit == 0: | |
continue | |
if FILL_BETWEEN: | |
ax.fill_between( | |
[ | |
(max_column - digit) * column_width, | |
max_column * column_width, | |
], | |
row * row_width, | |
(row + 1) * row_width, | |
color="black", | |
alpha=0.5, | |
) | |
continue | |
x_start = (max_column - digit) * column_width | |
x_end = max_column * column_width | |
y_bottom = row * row_width | |
y_top = (row + 1) * row_width | |
ax.plot( | |
[x_start, x_end], [y_top, y_top], color="black", linewidth=5, | |
) | |
ax.plot( | |
[x_start, x_end], [y_bottom, y_bottom], color="black", linewidth=5, | |
) | |
for bar_position in range(0, digit + 1): | |
x_position = (max_column - bar_position) * column_width | |
ax.plot( | |
[x_position, x_position], | |
[y_bottom, y_top], | |
color="black", | |
linewidth=5, | |
) | |
buffer = 0.5 ** 7 | |
ax.set_xlim( | |
-buffer * max_column * column_width, | |
max_column * column_width * (1 + buffer), | |
) | |
ax.set_ylim( | |
-buffer * max_row * row_width, max_row * row_width * (1 + buffer) | |
) | |
ax.set_aspect("equal") | |
margin = 0.5 ** 6 | |
figure.subplots_adjust( | |
left=margin, | |
bottom=margin, | |
right=1 - margin, | |
top=1 - margin, | |
wspace=0, | |
hspace=0, | |
) | |
if FILL_BETWEEN: | |
filename = "grid.pdf" | |
else: | |
filename = "grid-no-fill.pdf" | |
figure.savefig(filename) | |
print(f"Saved {filename}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment