<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Sentiment Analysis
Step1:  trying for several targets
Step2:  Plots
Step3:  Scatterplot
Scatter plot of sentiments of the last 100 tweets sent out by each news organization, ranging from -1.0 to 1.0, where a score of 0 expresses a neutral sentiment, -1 the most negative sentiment possible, and +1 the most positive sentiment possible.
Step4:  3. bar plot
visualizing the overall sentiments of the last 100 tweets from each organization. For this plot, you will again aggregate the compound sentiments analyzed by VADER.
<ASSISTANT_TASK:>
Python Code:
# Dependencies
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import json
import tweepy
import time
import seaborn as sns
%pylab notebook
# Initialize Sentiment Analyzer
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
# Twitter API Keys
consumer_key = "8kRQQdDT8zGpyOBTUbXqGF2nc"
consumer_secret = "1D2oGovKe15PwLTKEAlI7ao4nAnHqSYfkGH5mQAdx1T7BUdEmX"
access_token = "68786821-99qoOdGVdmeskFhyanhuj5G1UgTjLXy3zsHtmBTB4"
access_token_secret = "WrIEOcbavzeNmeEoCH2ZxfqIMlB1KbMYCVNnihgQTUC0c"
# Setup Tweepy API Authentication
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, parser=tweepy.parsers.JSONParser())
# Target Account
target_terms = ["@CNN", "@BBC", "@CBS",
                "@Fox", "@nytimes"]
# Counter
counter = 1
# Variables for holding sentiments
sentiments = []
# Loop through the list of targets 
for target in target_terms:
    # Get all tweets from home feed
    public_tweets = api.user_timeline(target, count = 100) #(total 100 tweets)
    tweetnumber = 1
    
    # Loop through all tweets 
    for tweet in public_tweets:
        # Print Tweets
        print("Tweet %s: %s" % (counter, tweet["text"]))
        
        # Run Vader Analysis on each tweet
        compound = analyzer.polarity_scores(tweet["text"])["compound"]
        pos = analyzer.polarity_scores(tweet["text"])["pos"]
        neu = analyzer.polarity_scores(tweet["text"])["neu"]
        neg = analyzer.polarity_scores(tweet["text"])["neg"]
        tweets_ago = tweetnumber
        
        # Add sentiments for each tweet into an array
        sentiments.append({"User": target,
                           "Date": tweet["created_at"], 
                           "Compound": compound,
                           "Positive": pos,
                           "Negative": neu,
                           "Neutral": neg,
                           "Tweets Ago": tweetnumber})
        
        
        # Add to counter 
        tweetnumber += 1 
        counter = counter + 1
        
# sentiments to DataFrame
sentiments_pd = pd.DataFrame.from_dict(sentiments)
sentiments_pd.head(25)
#Checking that it works 
#sentiments_pd.describe()
#sentiments_pd.tail()
sentiments_pd["User"].describe()
# Convert sentiments to DataFrame
sentiments_pd = pd.DataFrame.from_dict(sentiments)
sentiments_pd.head()
sentiments_pd.columns
Explanation: Sentiment Analysis
End of explanation
sentiments_pd.to_csv("newsTweets.csv")
Explanation: trying for several targets
End of explanation
# Firt : Create plot - general view
plt.plot(np.arange(len(sentiments_pd["Compound"])),
         sentiments_pd["Compound"], marker="o", linewidth=0.5,
         alpha=0.8)
# # Incorporate the other graph properties
plt.title("Sentiment Analysis of Tweets (%s) for %s" % (time.strftime("%x"), target_terms))
plt.ylabel("Tweet Polarity")
plt.xlabel("Tweets Ago")
plt.show()
plt.savefig('Overall.png')
Explanation: Plots
End of explanation
news_colors = {"@CNN": "red", 
               "@BBC": "blue",
               "@CBS": "yellow",
                "@Fox": "lightblue",
               "@nytimes" : "green"}
# Create a scatterplot of,
sns.set()
plt.figure(figsize = (10,6))
plt.xlabel ("tweet Ago", fontweight = 'bold')
plt.ylabel ("Tweet Polarity", fontweight ='bold')
plt.title ("Sentiment Analysis")
plt.xlim (102, -2, -1)
plt.ylim(-1,1)
for target_terms in news_colors.keys(): 
    df = sentiments_pd[sentiments_pd["User"] == target_terms]
    sentiment_analysis = plt.scatter(df["Tweets Ago"],df["Compound"], label = target_terms, color = news_colors[target_terms], edgecolor = "black", s=125)
plt.legend(bbox_to_anchor = (1,1), title = 'Media Sources')
plt.show()
sentiment_analysis.figure.savefig('SentimentAnalysis.png')
Explanation: Scatterplot
Scatter plot of sentiments of the last 100 tweets sent out by each news organization, ranging from -1.0 to 1.0, where a score of 0 expresses a neutral sentiment, -1 the most negative sentiment possible, and +1 the most positive sentiment possible.
End of explanation
# finding average with group by 
#taking user and finding the average of compound
groupbyagency = sentiments_pd.groupby("User")["Compound"].mean()
# count at 0
df[(df["Compound"]==0)].groupby("newsOutlet").count()
groupbyagency_df = pd.DataFrame(groupbyagency)
groupbyagency_df
data = [0.099411, 0.203394, -0.087430 , 0.179426, 0.039392]
#sns.barplot(x = "data", data = data, palette = news_colors)
sns.barplot(x = data, y = data, data = groupbyagency_df, orient = "h")
plt.title ("Sentiment Analysis")
plt.show()
plt.savefig('SentimentAnalysisII.png')
Explanation: 3. bar plot
visualizing the overall sentiments of the last 100 tweets from each organization. For this plot, you will again aggregate the compound sentiments analyzed by VADER.
End of explanation
<END_TASK>