Skip to content

Instantly share code, notes, and snippets.

@drazenz
drazenz / list-to-file-1.py
Last active August 23, 2021 14:30
How to write lists to a file in Python
cities = ['New York', 'London', 'Singapore']
with open('output.txt', 'w') as output_file:
for city in cities:
print(city, file=output_file)
import string
def print_center(text:str) -> None:
term_len = 80
printable = ''.join([c for c in text if c in string.printable])
lines = printable.splitlines()
if len(lines) > 1:
for line in lines: print_center(line)
elif len(printable) > term_len:
import json
import requests
import traceback
def fetch_post(post_url):
try:
res = requests.get(post_url + '?format=json').text
res = res[res.find('{'):]
data = json.loads(res)
return data
plt.figure(figsize=(10, 10))
corrplot(data.corr())
bin_labels = ['Low (0-100)', 'Medium (100-150)', 'High (150+)']
data['horsepower-group'] = pd.cut(
data['horsepower'],
bins=[0, 100, 150, data['horsepower'].max()],
labels=bin_labels
)
data['cnt'] = np.ones(len(data))
g = data.groupby(['horsepower-group', 'make']).count()[['cnt']].reset_index().replace(np.nan, 0)
plt.figure(figsize=(3, 11))
plot_grid = plt.GridSpec(1, 15, hspace=0.2, wspace=0.1) # Setup a 1x15 grid
ax = plt.subplot(plot_grid[:,:-1]) # Use the leftmost 14 columns of the grid for the main plot
ax.scatter(
x=x.map(x_to_num), # Use mapping for x
y=y.map(y_to_num), # Use mapping for y
s=size * size_scale, # Vector of square sizes, proportional to size parameter
c=color.apply(value_to_color), # Vector of square colors, mapped to color palette
marker='s' # Use square as scatterplot marker
)
ax.set_xlim([-0.5, max([v for v in x_to_num.values()]) + 0.5])
ax.set_ylim([-0.5, max([v for v in y_to_num.values()]) + 0.5])
@drazenz
drazenz / step_4.py
Last active October 10, 2021 03:57
n_colors = 256 # Use 256 colors for the diverging color palette
palette = sns.diverging_palette(20, 220, n=n_colors) # Create the palette
color_min, color_max = [-1, 1] # Range of values that will be mapped to the palette, i.e. min and max possible correlation
def value_to_color(val):
val_position = float((val - color_min)) / (color_max - color_min) # position of value in the input range, relative to the length of the input range
ind = int(val_position * (n_colors - 1)) # target index in the color palette
return palette[ind]
ax.scatter(
ax.grid(False, 'major')
ax.grid(True, 'minor')
ax.set_xticks([t + 0.5 for t in ax.get_xticks()], minor=True)
ax.set_yticks([t + 0.5 for t in ax.get_yticks()], minor=True)
# Step 1 - Make a scatter plot with square markers, set column names as labels
def heatmap(x, y, size):
fig, ax = plt.subplots()
# Mapping from column names to integer coordinates
x_labels = [v for v in sorted(x.unique())]
y_labels = [v for v in sorted(y.unique())]
x_to_num = {p[1]:p[0] for p in enumerate(x_labels)}
y_to_num = {p[1]:p[0] for p in enumerate(y_labels)}