Musings of a dad with too much time on his hands and not enough to do. Wait. Reverse that.

Month: March 2019 (Page 1 of 2)

Watermarking Matplotlib charts

A few weeks ago, I read an interesting article about watermarking your ggplot charts in R. R is certainly a fantastic tool, but as my go-to language for visualizations these days is Python, I had to ask myself, “self, how would you watermark your matplotlib charts?” Well, one answer is the text method of the Figure object.

Consider this polar chart I wrote some time ago:

colleges = ['College A', 'College B', 'College C', 'College D', 'College E']
scores = [76, 54, 58, 63, 65]

theta = np.arange(len(colleges))/float(len(colleges)) * 2 * np.pi
fig = plt.figure(figsize=(8, 8))
ax = plt.subplot(111, projection='polar')
ax.plot(theta, scores, color='green', marker='o')
ax.plot([theta[0], theta[-1]], [scores[0], scores[-1]], 'g-')  # hack to complete the circle
ax.set_rmax(max(scores) + 5)
ax.set_rticks(np.arange(0, max(scores) + 5, step=10))
ax.set_xticks(theta)
labels = ax.set_xticklabels(colleges)

# hack to get the labels to show nicely
[l.set_ha('right') for l in labels if l.get_text() in ['College C', 'College D']]
[l.set_ha('left') for l in labels if l.get_text() in ['College A']]

for i, txt in enumerate(scores):
    ax.annotate(txt, (theta[i], scores[i]))

ax.grid(True)

ax.set_title('College Scorecard')
plt.tight_layout()

# watermarking my chart
fig.text(0.95, 0.06, 'DadOverflow.com',
         fontsize=12, color='gray',
         ha='right', va='bottom', alpha=0.5)

plt.show()

I’ve highlighted the part of the code that watermarks the chart. This code produces the following chart:

Hey, how about that cool watermark in the lower right-hand corner? Snazzy, right? One challenge I’ve found is that as you change the size of your chart, you’ll have to play around a little with the x and y coordinates of your watermark. Nevertheless, this seems to me like a great way to brand your charts.

Two techniques to replace text with Python

Python makes it pretty darn easy to replace text in a string:

s = 'The quick brown studebaker jumps over the lazy dog'
print(s.replace('studebaker', 'fox'))

However, when I’m cleaning larger data sets, I find myself perform multiple replacement operations. You can chain replace operations together:

s = 'The quick brown studebaker jumps over the lazy chupacabra'
print(s.replace('studebaker', 'fox').replace('chupacabra', 'dog'))

…but if you have a lot of text to replace, chaining replace operations together can go sideways pretty fast. Here are two techniques I’ve found to replace a large number of text in a cleaner way.

Using the Zip Function

The zip function is a neat technique to join tuples together for easy iteration. In the case of replacing text, we have a tuple of the text needing to be replaced and a tuple of the text that will be the substitutes:

s = 'The quick blue jackalope jumps under the lazy chupacabra'

old_words = ('blue', 'jackalope', 'under', 'chupacabra')
new_words = ('brown', 'fox', 'over', 'dog')

for check, rep in zip(old_words, new_words):
    s = s.replace(check, rep)
    
print(s)

Using Replace in a Pandas Dataframe

Often, I’ll have text in a pandas dataframe that I need to replace. For such circumstances, pandas provides a variety of solutions. I’ve found using a dictionary can be a clean way to solve this problem:

s = 'The quick blue jackalope jumps under the lazy chupacabra'
df = pd.DataFrame(s.split(' '), columns=['word'])
print(df)  # print the error-laden dataframe

replacements = {'blue': 'brown', 'jackalope': 'fox', 'under': 'over', 'chupacabra': 'dog'}
df['word'] = df.word.replace(replacements)
print(df)  # now print the cleaned up dataframe

Happy replacing!

Building resiliency in your children

Boy, that kid is resilient

Some time ago, I posted some thoughts on why a person should pursue genealogy as a hobby. Well, according to researchers, here’s another good reason: it helps build resiliency in your children!

Here’s a salient quote from the article:

Researchers speculated that children who know about their own family history have a stronger feeling of being part of something bigger than themselves. Children who knew family history felt part of a larger family.

Daily Herald, 23 February 2019

I wholeheartedly concur. If not you, then some recent or distant ancestor undoubtedly struggled against insurmountable odds and prevailed to give you and your family a fighting shot at success. I think knowing that struggle and sacrifice does build hope and promise in your children and bonds your family even more tightly.

So where do you start? The article suggested a few questions you can pose to your children:

  • Do you know where your grandparents grew up?
  • Do you know where your parents met?

Seems like a good start to me!

(Thanks to Dick Eastman for linking to the article.)

« Older posts

© 2024 DadOverflow.com

Theme by Anders NorenUp ↑