Icon

My Python

KNIME & Python - How to Make a large Plot with Two Different Y-axis in Python with Matplotlib and Date X-Axis

KNIME & Python - How to Make a large Plot with Two Different Y-axis in Python with Matplotlib and Date X-Axis
https://forum.knime.com/t/hybrid-graph/64012/2?u=mlauber71

adapted from: https://cmdlinetips.com/2019/10/how-to-make-a-plot-with-two-different-y-axis-in-python-with-matplotlib/



CODE SOURCE FOR RESISTANCE+SUPPORT LINESimport pandas as pd# Load local CSV file and parse into dataframe objectbtc = pd.read_csv('BTC-USD.06282017-06282022.csv')# Parse date as DateTimebtc['Date'] = pd.to_datetime(btc['Date'])# Set the date as the indexbtc.set_index(['Date'], inplace=True)# View the resultsprint(btc)# Output Open High ... Adj Close VolumeDate ... 2017-06-26 2567.560059 2588.830078 ... 2506.469971 33939130242017-07-03 2498.560059 2916.139893 ... 2518.439941 58317489922017-07-10 2525.250000 2537.159912 ... 1929.819946 74531210242017-07-17 1932.619995 2900.699951 ... 2730.399902 99479900802017-07-24 2732.699951 2897.449951 ... 2757.179932 6942860928... ... ... ... ... ...2022-06-06 29910.283203 31693.291016 ... 26762.648438 2159296459342022-06-13 26737.578125 26795.589844 ... 20553.271484 3096859152502022-06-20 20553.371094 21783.724609 ... 21027.294922 1759090561222022-06-27 21028.238281 21478.089844 ... 20280.634766 423472308682022-06-29 20291.271484 20360.972656 ... 20055.185547 24722872320[263 rows x 6 columns]# Convert adjusted closing price to numpy arraybtc_prices = np.array(btc["Adj Close"])print("BTC Prices:\n", btc_prices)# Perform cluster analysisK = 6kmeans = KMeans(n_clusters=6).fit(btc_prices.reshape(-1, 1))# predict which cluster each price is inclusters = kmeans.predict(btc_prices.reshape(-1, 1))print("Clusters:\n", clusters)# View ouputBTC Prices: [ 2506.469971 2518.439941 1929.819946 2730.399902 2757.179932 3213.939941 4073.26001 4087.659912 4382.879883 4582.959961 ... lots of extra data rows here ... 39716.953125 39469.292969 38469.09375 34059.265625 31305.113281 30323.722656 29445.957031 29906.662109 26762.648438 20553.271484 21027.294922 20280.634766 20055.185547]Clusters: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 5 5 3 3 5 5 3 5 5 5 5 5 5 5 5 5 5 5 0 0 5 5 5 5 5 5 0 5 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 0 0 0 0 0 0 0 5 5 5 5 5 5 5 5 5 0 0 0 0 0 0 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 3 3 3 3 3 3 3 3 2 2 2 2 2 2 1 4 1 1 4 4 4 4 4 4 1 4 4 1 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 4 4 4 4 4 4 4 4 1 1 1 1 1 1 1 2 2 1 1 2 2 2 2 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3]# Assigns plotly as visualization enginepd.options.plotting.backend = 'plotly'# Arbitrarily 6 colors for our 6 clusterscolors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo']# Create Scatter plot, assigning each point a color based# on it's grouping where group_number == index of color.fig = btc.plot.scatter( x=btc.index, y="Adj Close", color=[colors[i] for i in clusters],)# Configure some styleslayout = go.Layout( plot_bgcolor='#efefef', showlegend=False, # Font Families font_family='Monospace', font_color='#000000', font_size=20, xaxis=dict( rangeslider=dict( visible=False )))fig.update_layout(layout)# Display plot in local browser windowfig.show()# Create list to hold values, initialized with infinite valuesmin_max_values = []# init for each cluster groupfor i in range(6): # Add values for which no price could be greater or less min_max_values.append([np.inf, -np.inf])# Print initial valuesprint(min_max_values)# Get min/max for each clusterfor i in range(len(btc_prices)): # Get cluster assigned to price cluster = clusters[i] # Compare for min value if btc_prices[i] < min_max_values[cluster][0]: min_max_values[cluster][0] = btc_prices[i] # Compare for max value if btc_prices[i] > min_max_values[cluster][1]: min_max_values[cluster][1] = btc_prices[i]# Print resulting valuesprint(min_max_values)# Output[[inf, -inf], [inf, -inf], [inf, -inf], [inf, -inf], [inf, -inf], [inf, -inf]][[15455.400391, 26762.648438], [41247.824219, 51753.410156], [29445.957031, 39974.894531], [1929.819946, 7564.345215],[54771.578125, 65466.839844], [7679.867188, 14156.400391]]import plotly.graph_objects as go# Again, assign an arbitrary color to each of the 6 clusterscolors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo']# Create Scatter plot, assigning each point a color where# point group = color index.fig = btc.plot.scatter( x=btc.index, y="Adj Close", color=[colors[i] for i in clusters],)# Add horizontal linesfor cluster_min, cluster_max in min_max_values: fig.add_hline(y=cluster_min, line_width=1, line_color="blue") fig.add_hline(y=cluster_max, line_width=1, line_color="blue")# Add a trace of the price for better clarityfig.add_trace(go.Trace( x=btc.index, y=btc['Adj Close'], line_color="black", line_width=1))# Make it prettylayout = go.Layout( plot_bgcolor='#efefef', showlegend=False, # Font Families font_family='Monospace', font_color='#000000', font_size=20, xaxis=dict( rangeslider=dict( visible=False )))fig.update_layout(layout)fig.show()print("Initial Min/Max Values:\n", min_max_values)# Create container for combined valuesoutput = []# Sort based on cluster minimums = sorted(min_max_values, key=lambda x: x[0])# For each cluster get average offor i, (_min, _max) in enumerate(s): # Append min from first cluster if i == 0: output.append(_min) # Append max from last cluster if i == len(min_max_values) - 1: output.append(_max) # Append average from cluster and adjacent for all others else: output.append(sum([_max, s[i+1][0]]) / 2)print("Sorted Min/Max Values:\n", output)# Resulting outputInitial Min/Max Values:[[1929.819946, 7564.345215], [41247.824219, 51753.410156], [7679.867188, 14156.400391], [29445.957031, 39974.894531],[54771.578125, 65466.839844], [15455.400391, 26762.648438]]Sorted Min/Max Values:[1929.819946, 7622.106201500001, 14805.900391, 28104.3027345, 40611.359375, 53262.4941405, 65466.839844]# Add horizontal linesfor cluster_avg in output: fig.add_hline(y=cluster_avg, line_width=1, line_color="blue")# Add horizontal lines for cluster_avg in output[1:-1]: fig.add_hline(y=cluster_avg, line_width=1, line_color="blue")# create a list to contain output valuesvalues = []# Define a range of cluster values to assessK = range(1, 10)# Performa a clustering using each value, save inertia_ value from eachfor k in K: kmeans_n = KMeans(n_clusters=k) kmeans_n.fit(btc_prices.reshape(-1, 1)) values.append(kmeans_n.inertia_)# Output[80453452183.20088, 10385720870.392435, 4899414919.598458, 3200341434.3973494, 2038101574.9904993, 1230938654.2410448,913656416.2350059, 711089387.2186545, 573668652.8908113]import plotly.graph_objects as go# Create initial figurefig = go.Figure()# Add line plot of inertia valuesfig.add_trace(go.Trace( x=list(K), y=values, line_color="black", line_width=1))# Make it prettylayout = go.Layout( plot_bgcolor='#efefef', showlegend=False, # Font Families font_family='Monospace', font_color='#000000', font_size=20, xaxis=dict( rangeslider=dict( visible=False )))fig.update_layout(layout)fig.show() MLAUBER'S DUAL-AXES PYTHON WORKFLOW (WITH MINOR MODIFICATION) DATA Image To Table Renderer to Image Table To Image Python graphics - linechart with two axis Python Script Excel Reader String to Date&Time Sorter String ToNumber (PMML) CODE SOURCE FOR RESISTANCE+SUPPORT LINESimport pandas as pd# Load local CSV file and parse into dataframe objectbtc = pd.read_csv('BTC-USD.06282017-06282022.csv')# Parse date as DateTimebtc['Date'] = pd.to_datetime(btc['Date'])# Set the date as the indexbtc.set_index(['Date'], inplace=True)# View the resultsprint(btc)# Output Open High ... Adj Close VolumeDate ... 2017-06-26 2567.560059 2588.830078 ... 2506.469971 33939130242017-07-03 2498.560059 2916.139893 ... 2518.439941 58317489922017-07-10 2525.250000 2537.159912 ... 1929.819946 74531210242017-07-17 1932.619995 2900.699951 ... 2730.399902 99479900802017-07-24 2732.699951 2897.449951 ... 2757.179932 6942860928... ... ... ... ... ...2022-06-06 29910.283203 31693.291016 ... 26762.648438 2159296459342022-06-13 26737.578125 26795.589844 ... 20553.271484 3096859152502022-06-20 20553.371094 21783.724609 ... 21027.294922 1759090561222022-06-27 21028.238281 21478.089844 ... 20280.634766 423472308682022-06-29 20291.271484 20360.972656 ... 20055.185547 24722872320[263 rows x 6 columns]# Convert adjusted closing price to numpy arraybtc_prices = np.array(btc["Adj Close"])print("BTC Prices:\n", btc_prices)# Perform cluster analysisK = 6kmeans = KMeans(n_clusters=6).fit(btc_prices.reshape(-1, 1))# predict which cluster each price is inclusters = kmeans.predict(btc_prices.reshape(-1, 1))print("Clusters:\n", clusters)# View ouputBTC Prices: [ 2506.469971 2518.439941 1929.819946 2730.399902 2757.179932 3213.939941 4073.26001 4087.659912 4382.879883 4582.959961 ... lots of extra data rows here ... 39716.953125 39469.292969 38469.09375 34059.265625 31305.113281 30323.722656 29445.957031 29906.662109 26762.648438 20553.271484 21027.294922 20280.634766 20055.185547]Clusters: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 5 5 3 3 5 5 3 5 5 5 5 5 5 5 5 5 5 5 0 0 5 5 5 5 5 5 0 5 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 0 0 0 0 0 0 0 5 5 5 5 5 5 5 5 5 0 0 0 0 0 0 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 3 3 3 3 3 3 3 3 2 2 2 2 2 2 1 4 1 1 4 4 4 4 4 4 1 4 4 1 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 4 4 4 4 4 4 4 4 1 1 1 1 1 1 1 2 2 1 1 2 2 2 2 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3]# Assigns plotly as visualization enginepd.options.plotting.backend = 'plotly'# Arbitrarily 6 colors for our 6 clusterscolors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo']# Create Scatter plot, assigning each point a color based# on it's grouping where group_number == index of color.fig = btc.plot.scatter( x=btc.index, y="Adj Close", color=[colors[i] for i in clusters],)# Configure some styleslayout = go.Layout( plot_bgcolor='#efefef', showlegend=False, # Font Families font_family='Monospace', font_color='#000000', font_size=20, xaxis=dict( rangeslider=dict( visible=False )))fig.update_layout(layout)# Display plot in local browser windowfig.show()# Create list to hold values, initialized with infinite valuesmin_max_values = []# init for each cluster groupfor i in range(6): # Add values for which no price could be greater or less min_max_values.append([np.inf, -np.inf])# Print initial valuesprint(min_max_values)# Get min/max for each clusterfor i in range(len(btc_prices)): # Get cluster assigned to price cluster = clusters[i] # Compare for min value if btc_prices[i] < min_max_values[cluster][0]: min_max_values[cluster][0] = btc_prices[i] # Compare for max value if btc_prices[i] > min_max_values[cluster][1]: min_max_values[cluster][1] = btc_prices[i]# Print resulting valuesprint(min_max_values)# Output[[inf, -inf], [inf, -inf], [inf, -inf], [inf, -inf], [inf, -inf], [inf, -inf]][[15455.400391, 26762.648438], [41247.824219, 51753.410156], [29445.957031, 39974.894531], [1929.819946, 7564.345215],[54771.578125, 65466.839844], [7679.867188, 14156.400391]]import plotly.graph_objects as go# Again, assign an arbitrary color to each of the 6 clusterscolors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo']# Create Scatter plot, assigning each point a color where# point group = color index.fig = btc.plot.scatter( x=btc.index, y="Adj Close", color=[colors[i] for i in clusters],)# Add horizontal linesfor cluster_min, cluster_max in min_max_values: fig.add_hline(y=cluster_min, line_width=1, line_color="blue") fig.add_hline(y=cluster_max, line_width=1, line_color="blue")# Add a trace of the price for better clarityfig.add_trace(go.Trace( x=btc.index, y=btc['Adj Close'], line_color="black", line_width=1))# Make it prettylayout = go.Layout( plot_bgcolor='#efefef', showlegend=False, # Font Families font_family='Monospace', font_color='#000000', font_size=20, xaxis=dict( rangeslider=dict( visible=False )))fig.update_layout(layout)fig.show()print("Initial Min/Max Values:\n", min_max_values)# Create container for combined valuesoutput = []# Sort based on cluster minimums = sorted(min_max_values, key=lambda x: x[0])# For each cluster get average offor i, (_min, _max) in enumerate(s): # Append min from first cluster if i == 0: output.append(_min) # Append max from last cluster if i == len(min_max_values) - 1: output.append(_max) # Append average from cluster and adjacent for all others else: output.append(sum([_max, s[i+1][0]]) / 2)print("Sorted Min/Max Values:\n", output)# Resulting outputInitial Min/Max Values:[[1929.819946, 7564.345215], [41247.824219, 51753.410156], [7679.867188, 14156.400391], [29445.957031, 39974.894531],[54771.578125, 65466.839844], [15455.400391, 26762.648438]]Sorted Min/Max Values:[1929.819946, 7622.106201500001, 14805.900391, 28104.3027345, 40611.359375, 53262.4941405, 65466.839844]# Add horizontal linesfor cluster_avg in output: fig.add_hline(y=cluster_avg, line_width=1, line_color="blue")# Add horizontal lines for cluster_avg in output[1:-1]: fig.add_hline(y=cluster_avg, line_width=1, line_color="blue")# create a list to contain output valuesvalues = []# Define a range of cluster values to assessK = range(1, 10)# Performa a clustering using each value, save inertia_ value from eachfor k in K: kmeans_n = KMeans(n_clusters=k) kmeans_n.fit(btc_prices.reshape(-1, 1)) values.append(kmeans_n.inertia_)# Output[80453452183.20088, 10385720870.392435, 4899414919.598458, 3200341434.3973494, 2038101574.9904993, 1230938654.2410448,913656416.2350059, 711089387.2186545, 573668652.8908113]import plotly.graph_objects as go# Create initial figurefig = go.Figure()# Add line plot of inertia valuesfig.add_trace(go.Trace( x=list(K), y=values, line_color="black", line_width=1))# Make it prettylayout = go.Layout( plot_bgcolor='#efefef', showlegend=False, # Font Families font_family='Monospace', font_color='#000000', font_size=20, xaxis=dict( rangeslider=dict( visible=False )))fig.update_layout(layout)fig.show() MLAUBER'S DUAL-AXES PYTHON WORKFLOW (WITH MINOR MODIFICATION) DATA Image To Table Renderer to Image Table To Image Python graphics - linechart with two axis Python Script Excel Reader String to Date&Time Sorter String ToNumber (PMML)

Nodes

Extensions

Links