Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alternative solution (Chapter 1, Exercise 3) #62

Open
labdmitriy opened this issue Jul 12, 2022 · 4 comments
Open

Alternative solution (Chapter 1, Exercise 3) #62

labdmitriy opened this issue Jul 12, 2022 · 4 comments

Comments

@labdmitriy
Copy link
Contributor

labdmitriy commented Jul 12, 2022

Hi @rougier,

Because Discussions are not enabled for this repository, I decided to share my alternative solution for ridgeline plot exercise as separate issue, because it is a slightly different approach, for clarity I added the comments for each step:

from matplotlib.patches import ConnectionPatch
import matplotlib.pyplot as plt
import numpy as np

# Initial function
def curve():
    n = np.random.randint(1,5)
    centers = np.random.normal(0.0,1.0,n)
    widths = np.random.uniform(5.0,50.0,n)
    widths = 10*widths/widths.sum()
    scales = np.random.uniform(0.1,1.0,n)
    scales /= scales.sum()
    X = np.zeros(500)
    x = np.linspace(-3,3,len(X))
    
    for center, width, scale in zip(centers, widths, scales):
        X = X + scale*np.exp(- (x-center)*(x-center)*width)
        
    return X

# Set random seed and subplots number
RANDOM_STATE = 25
np.random.seed(RANDOM_STATE)
rows = 50
cols = 3

# Configure figure and overlapping axes
fig, axs = plt.subplots(rows, cols, figsize=(10, rows*0.2), subplot_kw={'yticks': []})
plt.subplots_adjust(top=0.95, bottom=0.05, hspace=-0.5, wspace=0.1)

# Label columns with titles and rows with y-axis labels
# https://stackoverflow.com/a/25814386
row_names = [f'Serie {serie}' for serie in range(rows, 0, -1)]
col_names = [f'Value {value}' for value in range(1, cols + 1)]

for ax, name in zip(axs[:, 0], row_names):
    ax.set_ylabel(name, rotation=0, fontsize='small', loc='bottom', labelpad=40)
    
for ax, name in zip(axs[0], col_names):
    ax.set_title(name, fontsize='large', fontweight='bold', loc='left', pad=20)

# Control the degree of "softness/pastelness" of the colors (if required)
# https://stackoverflow.com/a/72289062
c = 0
colors = (1. - c) * plt.get_cmap('Spectral')(np.linspace(0, 1, rows)) + c * np.ones((rows, 4))
colors = colors[::-1]

# Plot graphs from left to right, from top to bottom
for idx in range(rows * cols):
    i = idx // cols
    j = idx % cols
    
    ax = axs[i][j]
    ax.set_facecolor('none')
    ax.spines[['left', 'top', 'right', 'bottom']].set_visible(False)
    
    if i != rows - 1:
        ax.get_xaxis().set_visible(False)
    
    y = curve()
    x = np.linspace(-3, 3, y.size)
    ax.plot(x, y, color='k', linewidth=1)
    ax.fill_between(x, y, color=colors[i])
    ax.set_zorder(i)

# Plot vertical lines for each column of subplots
for col_idx in range(cols):
    coords = axs[0][col_idx].get_position()
    zero_x_coords = (coords.x1 + coords.x0) / 2
    conn = ConnectionPatch(xyA=(zero_x_coords, 0.99), xyB=(0, 0), 
                           coordsA='figure fraction', coordsB='data', 
                           axesA=axs[0, col_idx], axesB=axs[rows-1, col_idx],
                           zorder=rows, linewidth=0.5, linestyle=(0, (8, 2)), color='k')
    fig.add_artist(conn)

plt.show()

Output image you can find in Jupyter notebook with exercises for Chapter 1.

Thank you.

@rougier
Copy link
Owner

rougier commented Jul 13, 2022

I did not realize I need to allow discussions to have dicussion. I never use them yet. Tell me if you prefer discussion, else, we can discuss here.

@rougier
Copy link
Owner

rougier commented Jul 13, 2022

Nice. I think it might be a bit slower because of the several axis but it's worth to be included in the book if you're ok (you will need to add your name/copyright at the top of the file). Then we could modify the caption in the exercise to explain that you can have a single axis solution or several axis solution. My only worry is the vertical lines that use the ConnectionPatch with quite complex arguments (it's might be a bit too early in the book). But since it is an alternative solution, maybe it is not that important.

@labdmitriy
Copy link
Contributor Author

I did not realize I need to allow discussions to have dicussion. I never use them yet. Tell me if you prefer discussion, else, we can discuss here.

It was just an explanation why I created an issue that is probably not an issue but just a sharing the alternative solution :)
So probably it will be more convenient to separate issues and discussions in the future.

Nice. I think it might be a bit slower because of the several axis but it's worth to be included in the book if you're ok (you will need to add your name/copyright at the top of the file). Then we could modify the caption in the exercise to explain that you can have a single axis solution or several axis solution.

Oh great, then I can create PR. What is the best place and the name of the file for this solution?

My only worry is the vertical lines that use the ConnectionPatch with quite complex arguments (it's might be a bit too early in the book). But since it is an alternative solution, maybe it is not that important.

I am trying to solve the exercises as best as I can myself and then I study your solutions, and my solution was based on the relevant information I found in internet. I didn't know about different coordinates which are used in the arguments of ConnectionPatch, and also the information about coordinates in the Chapter 2, so maybe it will be additional motivation to come back to this solution after Chapter 2 :)
By the way, I found that the solution for Exercise 1 from Chapter 1 was the hardest one for now and to be honest I didn't understand some part of the code provided :) But it was very useful anyway if you try to solve the exercises yourself at first.

@rougier
Copy link
Owner

rougier commented Jul 25, 2022

Sorry, late again. for the PR, may add "-alternative" for the script and inside the book, it can a single sentence stating that a different solution wiht individual axis can also be made.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants