0

I want to create two seperate lines which shows stock prices and sentiment scores.

This my code:

import matplotlib.pyplot as plt

# Create a figure and axis
fig, ax = plt.subplots(figsize=(10, 6))

# Plot stock prices
ax.plot(tsla['Date'], tsla['Close'], color='blue', label='Stock Prices')

# Create a second y-axis
ax2 = ax.twinx()

# Plot sentiment scores
ax2.plot(tsla['Date'], tsla['sentiment_score'], color='red', label='Sentiment Scores')

# Set labels and titles
ax.set_xlabel('Date')
ax.set_ylabel('Stock Prices', color='blue')
ax2.set_ylabel('Sentiment Scores', color='red')
plt.title('Stock Prices and Sentiment Scores Over Time')

# Add legends
lines = ax.get_lines() + ax2.get_lines()
labels = [line.get_label() for line in lines]
plt.legend(lines, labels, loc='upper left')

# Rotate x-axis tick labels for better readability
plt.xticks(rotation=45)

# Show the plot
plt.show()
This my unexpected output:

enter image description here

This my sample data:

      Date Stock Name        Open       Close        High    Volume  \

12 2022-02-01 TSLA 311.736664 310.416656 314.566681 73138200
33 2022-03-01 TSLA 289.893341 288.123322 296.626678 74766900
50 2022-04-01 TSLA 360.383331 361.529999 364.916656 54263100
67 2022-06-01 TSLA 251.720001 246.789993 257.326660 77247900
86 2022-07-01 TSLA 227.000000 227.263336 230.229996 74460300

sentiment_score  

12 17.0517
33 16.8564
50 11.4832
67 12.9977
86 11.1603

2 Answers2

1

Here You go, just format as necessary:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
from datetime import datetime, timedelta


#your supplied data
#Date Stock Name        Open       Close        High    Volume/
#12 2022-02-01 TSLA 311.736664 310.416656 314.566681 73138200
#33 2022-03-01 TSLA 289.893341 288.123322 296.626678 74766900
#50 2022-04-01 TSLA 360.383331 361.529999 364.916656 54263100
#67 2022-06-01 TSLA 251.720001 246.789993 257.326660 77247900
#86 2022-07-01 TSLA 227.000000 227.263336 230.229996 74460300

#sentiment_score  
#12 17.0517
#33 16.8564
#50 11.4832
#67 12.9977
#86 11.1603
#
# Define the data for the dataframe
data = {
    'Date': ['2022-02-01', '2022-03-01', '2022-04-01', '2022-06-01', '2022-07-01'],
    'Stock Name': ['TSLA', 'TSLA', 'TSLA', 'TSLA', 'TSLA'],
    'Open': [311.736664, 289.893341, 360.383331, 251.720001, 227.000000],
    'Close': [310.416656, 288.123322, 361.529999, 246.789993, 227.263336],
    'High': [314.566681, 296.626678, 364.916656, 257.326660, 230.229996],
    'Volume': [73138200, 74766900, 54263100, 77247900, 74460300],
    'sentiment_score': [17.0517, 16.8564, 11.4832, 12.9977, 11.1603]
}

# Create the dataframe
df = pd.DataFrame(data)


# Convert the 'Date' column to datetime
df['Date'] = pd.to_datetime(df['Date'])

# Set the style of the plot
plt.style.use('seaborn-darkgrid')

# Create a new figure and a subplot
fig, ax1 = plt.subplots()

# Plot the Open, Close, and High prices
ax1.plot(df['Date'], df['Open'], label='Open', color='g')
ax1.plot(df['Date'], df['Close'], label='Close', color='b')
ax1.plot(df['Date'], df['High'], label='High', color='r')

# Set the y-axis label
ax1.set_ylabel('Price', color='g')

# Create a second y-axis that shares the same x-axis
ax2 = ax1.twinx()

# Plot the sentiment_score on the second y-axis
ax2.plot(df['Date'], df['sentiment_score'], label='Sentiment Score', color='c')

# Set the second y-axis label
ax2.set_ylabel('Sentiment Score', color='c')

# To set x-axis major locator to one per month
ax1.xaxis.set_major_locator(mdates.MonthLocator())

# To set x-axis major formatter to month-year
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%b-%Y'))

# Automatically adjust subplot params so that the subplot fits in to the figure area
fig.tight_layout()

# Add a legend to the plot
fig.legend(loc="upper left", bbox_to_anchor=(0,1), bbox_transform=ax1.transAxes)

# Rotate x-axis labels for better visibility
plt.xticks(rotation=45)

# Display the plot
plt.show()

# Here's another example: https://python-graph-gallery.com/line-chart-dual-y-axis-with-matplotlib/

Figure with stock prices and sentiment

0

    # I did myself like this btw

import matplotlib.pyplot as plt

# Extract TSLA data
tsla_data = tsla.loc[tsla["Stock Name"] == "TSLA"]

# Plotting
fig, ax1 = plt.subplots(figsize=(10, 6))

# Plotting High
ax1.plot(tsla_data["Date"], tsla_data["High"], color='blue', label='High')
ax1.set_xlabel('Date')
ax1.set_ylabel('High', color='blue')
ax1.tick_params('y', colors='blue')

# Create a second y-axis for sentiment scores
ax2 = ax1.twinx()
ax2.plot(tsla_data["Date"], tsla_data["sentiment_score"], color='red', alpha=0.6, linestyle='--', label='Sentiment Score')
ax2.set_ylabel('Sentiment Score', color='red')
ax2.tick_params('y', colors='red')

# Set plot title
plt.title('TSLA High and Sentiment Score Over Time')

# Add legend
lines = ax1.get_lines() + ax2.get_lines()
ax1.legend(lines, [line.get_label() for line in lines], loc='upper left')

# Show the plot
plt.show()

enter image description here