<jupyter_start><jupyter_text>3D scatter plot and related plotsIf this notebook is not in active (runnable) form, go to [here](https://github.com/fomightez/3Dscatter_plot-binder) and press `launch binder`.(This notebook also works in sessions launched from [here](https://github.com/fomightez/Python_basics_4nanocourse).)------If you haven't used one of these notebooks before, they're basically web pages in which you can write, edit, and run live code. They're meant to encourage experimentation, so don't feel nervous. Just try running a few cells and see what happens!.    Some tips:            Code cells have boxes around them.        To run a code cell, click on the cell and either click the  button on the toolbar above, or then hit Shift+Enter. The Shift+Enter combo will also move you to the next cell, so it's a quick way to work through the notebook. Selecting from the menu above the toolbar, Cell > Run All is a shortcut to trigger attempting to run all the cells in the notebook.        While a cell is running a * appears in the square brackets next to the cell. Once the cell has finished running the asterisk will be replaced with a number.        In most cases you'll want to start from the top of notebook and work your way down running each cell in turn. Later cells might depend on the results of earlier ones.        To edit a code cell, just click on it and type stuff. Remember to run the cell once you've finished editing.    ---- 3D scatter plot  Matplotlib-basedBased on [3D Scatterplot page](https://python-graph-gallery.com/370-3d-scatterplot/) from Yan Holtz's [Python Graph Gallery](https://python-graph-gallery.com/).<jupyter_code>%matplotlib inline
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# Dataset
df=pd.DataFrame({'X': range(1,101), 'Y': np.random.randn(100)*15+range(1,101), 'Z': (np.random.randn(100)*15+range(1,101))*2 })
 
# plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(df['X'], df['Y'], df['Z'], c='skyblue', s=60)
ax.view_init(50, 185)
plt.show()<jupyter_output><empty_output><jupyter_text>Using `%matplotlib notebook` in the classic notebook results in an rotatable, 3D view. Once you have a good view you can stop the interactivity by pressing on the blue stop button in the upper right and then in the next cell run the following code to get the values to put in `ax.view_init()` to reproduce that view point later:```pythonprint('ax.azim {}'.format(ax.azim))print('ax.elev {}'.format(ax.elev))```Change `%matplotlib notebook` back to `%matplotlib inline` for static view. **At present, in JupyterLab 3.1.1, all the code on this page will also display plots if you use `%matplotlib inline`.** Otherwise, if trying `%matplotlib notebook` in JupyterLab, you'll see errors about `IPython not defined` when trying to run the cells on this page in JupyterLab.The same holds for other plots below on this page.  A more thorough Matplotlib exampleNext example, based on [Part 3](https://jovianlin.io/data-visualization-seaborn-part-3/) of Jovian Lin's 3-part series [Data Visualization with Seaborn](https://jovianlin.io/data-visualization-seaborn-part-1/); however that section acknowledges the solution is based on Matplotlib:<jupyter_code>%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D

!curl -OL https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv
!curl -OL https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv
red_wine   = pd.read_csv('winequality-red.csv',   sep=';')
white_wine = pd.read_csv('winequality-white.csv', sep=';')
wines = pd.concat([red_wine,white_wine], ignore_index=True)
print("red wines:",len(red_wine))
print("white wines:",len(white_wine))
print("wines:",len(wines))

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')

xs = wines['residual sugar']
ys = wines['fixed acidity']
zs = wines['alcohol']
ax.scatter(xs, ys, zs, s=50, alpha=0.6, edgecolors='w')

ax.set_xlabel('Residual Sugar')
ax.set_ylabel('Fixed Acidity')
ax.set_zlabel('Alcohol')

plt.show()<jupyter_output>% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 84199  100 84199    0     0   207k      0 --:--:-- --:--:-- --:--:--  206k
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  258k  100  258k    0     0   843k      0 --:--:-- --:--:-- --:--:--  841k
red wines: 1599
white wines: 4898
wines: 6497<jupyter_text>The earlier parts of the code in the cell above were built-based on the earlier parts of that series.  3D, maptlotlib-based examples with a legendBased on https://stackoverflow.com/a/60621783/8508004<jupyter_code>%matplotlib inline
import seaborn as sns, numpy as np, pandas as pd, random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
sns.set_style("whitegrid", {'axes.grid' : False})

fig = plt.figure(figsize=(6,6))

ax = Axes3D(fig)

x = np.random.uniform(1,20,size=20)
y = np.random.uniform(1,100,size=20)
z = np.random.uniform(1,100,size=20)


g = ax.scatter(x, y, z, c=x, marker='o', depthshade=False, cmap='Paired')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

# produce a legend with the unique colors from the scatter
legend = ax.legend(*g.legend_elements(), loc="lower center", title="X Values", borderaxespad=-10, ncol=4)
ax.add_artist(legend)

plt.show()<jupyter_output><empty_output><jupyter_text>If you want to see the possibilities for `cmap` enter some nonsensical text as `cmap`, and it will list the possibilities. `viridis` is one<jupyter_code>%matplotlib inline
import seaborn as sns, numpy as np, pandas as pd, random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
sns.set_style("whitegrid", {'axes.grid' : False})

fig = plt.figure(figsize=(6,6))

ax = Axes3D(fig)

x = np.random.uniform(1,20,size=20)
y = np.random.uniform(1,100,size=20)
z = np.random.uniform(1,100,size=20)


g = ax.scatter(x, y, z, c=x, marker='o', depthshade=False, cmap='viridis')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

# produce a legend with the unique colors from the scatter
legend = ax.legend(*g.legend_elements(), loc="lower center", title="X Values", borderaxespad=-10, ncol=4)
ax.add_artist(legend)

plt.show()<jupyter_output><empty_output><jupyter_text>That last `cmap` is a gradient and if you'd prefer the legend be a color bar showing that gradient, you'd adjust the last code cell to read like this:<jupyter_code>%matplotlib inline
import seaborn as sns, numpy as np, pandas as pd, random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
sns.set_style("whitegrid", {'axes.grid' : False})

fig = plt.figure(figsize=(7.5,6))

ax = Axes3D(fig)

x = np.random.uniform(1,20,size=20)
y = np.random.uniform(1,100,size=20)
z = np.random.uniform(1,100,size=20)


g = ax.scatter(x, y, z, c=x, marker='o', depthshade=False, cmap='viridis')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

# produce a legend with a gradient colorbar on the right, based on https://stackoverflow.com/a/5495912/8508004
clb = fig.colorbar(g)
clb.ax.set_title('X') #adding title based on https://stackoverflow.com/a/33740567/8508004

plt.show()<jupyter_output><empty_output><jupyter_text>Note the width is also adjusted up (`figsize=(6,6)` to `figsize=(7.5,6)`) to account for the additonal colorbar legend on the right side of the resulting plot figure. ------ 2D, Seaborn-based approach, better?Based on [Part 3](https://jovianlin.io/data-visualization-seaborn-part-3/) of Jovian Lin's 3-part series [Data Visualization with Seaborn](https://jovianlin.io/data-visualization-seaborn-part-1/):    >"The better alternative — using Seaborn + toggle the size via the s parameter:"The earlier parts of the code below were built-based on the earlier parts of the series.<jupyter_code>%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D

!curl -OL https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv
!curl -OL https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv
red_wine   = pd.read_csv('winequality-red.csv',   sep=';')
white_wine = pd.read_csv('winequality-white.csv', sep=';')
wines = pd.concat([red_wine,white_wine], ignore_index=True)
print("red wines:",len(red_wine))
print("white wines:",len(white_wine))
print("wines:",len(wines))
plt.scatter(x = wines['fixed acidity'], 
            y = wines['alcohol'], 
            s = wines['residual sugar']*25, # <== 😀 Look here!
            alpha=0.4, 
            edgecolors='w')

plt.xlabel('Fixed Acidity')
plt.ylabel('Alcohol')
plt.title('Wine Alcohol Content - Fixed Acidity - Residual Sugar', y=1.05);<jupyter_output>% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 84199  100 84199    0     0   297k      0 --:--:-- --:--:-- --:--:--  297k
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  258k  100  258k    0     0   838k      0 --:--:-- --:--:-- --:--:--  835k
red wines: 1599
white wines: 4898
wines: 6497<jupyter_text>2D Using SeabornHowever, the code isn't actually using Seaborn (or at least not current Seaborn code) despite what the source material says. Seems to use Matplpotlib still. I have added use of Seaborn below.<jupyter_code>%matplotlib inline
import pandas as pd
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
!curl -OL https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv
!curl -OL https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv
red_wine   = pd.read_csv('winequality-red.csv',   sep=';')
white_wine = pd.read_csv('winequality-white.csv', sep=';')
wines = pd.concat([red_wine,white_wine], ignore_index=True)
print("red wines:",len(red_wine))
print("white wines:",len(white_wine))
print("wines:",len(wines))
ax = sns.scatterplot(x=wines['fixed acidity'], y=wines['alcohol'], size=wines['residual sugar'],
                     sizes=(25, 1450), alpha=0.4, legend = False, data=wines)
plt.title('Wine Alcohol Content - Fixed Acidity - Residual Sugar', y=1.05);<jupyter_output>% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 84199  100 84199    0     0   319k      0 --:--:-- --:--:-- --:--:--  319k
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  258k  100  258k    0     0   792k      0 --:--:-- --:--:-- --:--:--  792k
red wines: 1599
white wines: 4898
wines: 6497<jupyter_text>2D, seaborn-based with legend<jupyter_code>%matplotlib inline
import pandas as pd
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
!curl -OL https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv
!curl -OL https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv
red_wine   = pd.read_csv('winequality-red.csv',   sep=';')
white_wine = pd.read_csv('winequality-white.csv', sep=';')
wines = pd.concat([red_wine,white_wine], ignore_index=True)
print("red wines:",len(red_wine))
print("white wines:",len(white_wine))
print("wines:",len(wines))
ax = sns.scatterplot(x=wines['fixed acidity'], y=wines['alcohol'], size=wines['residual sugar'],
                     sizes=(25, 1450), alpha=0.4, data=wines)
#plt.legend(loc='best')
ax.legend(loc='center left', bbox_to_anchor=(1.25, 0.5), ncol=1) # based on https://stackoverflow.com/a/53737271/8508004
plt.title('Wine Alcohol Content - Fixed Acidity - Residual Sugar', y=1.05);<jupyter_output>% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 84199  100 84199    0     0   248k      0 --:--:-- --:--:-- --:--:--  247k
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  258k  100  258k    0     0   814k      0 --:--:-- --:--:-- --:--:--  814k
red wines: 1599
white wines: 4898
wines: 6497
{'fraction_non_alphanumeric': 0.1281532232949237, 'fraction_numerical': 0.03729367798193709, 'mean_word_length': 3.6930946291560103, 'pattern_counts': {'":': 0, '<': 30, '<?xml version=': 0, '>': 31, 'https://': 20, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '664549', 'license': 'MIT', 'n_tokens_mistral': 4747, 'n_tokens_neox': 4275, 'n_words': 1287, 'path': 'matplotlib3d-scatter-plots.ipynb', 'repo_name': 'fomightez/3Dscatter_plot-binder', 'size': '12844'}