Is there a way to plot the two different sources into same graph using MatplotLib?












0















I am creating clusters of top 10 most common words, and my filter_data has the set of word token list. I am able to plot the clusters of those 10 words after vectorizing but after comparing the lemmas of the most common words with filter data I want to plot the word token list in the same graph. So that all the words get plotted into their own relevant clusters. How should I do that?



I have tried vectorizing the data of most common words as well as the whole token list. Moreover, the top 10 most common words are being extracted out of the filter_data token list. In simple words I am trying to plot the semantic clusters using matplotlib.



import string
import re
import nltk
import PyPDF4
import numpy
from collections import Counter
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import PCA
from nltk.corpus import wordnet
import matplotlib.pyplot as plt

# Declaring all the variables
stopwords = nltk.corpus.stopwords.words('english')
# additional stopwords to be removed manually.
file = open('Corpus.txt', 'r')
moreStopwords = file.read().splitlines()
ps = nltk.PorterStemmer()
wn = nltk.WordNetLemmatizer()
data = PyPDF4.PdfFileReader(open('ReadyPlayerOne.pdf', 'rb'))

pageData = ''
for page in data.pages:
pageData += page.extractText()


def clean_text(text):
text = "".join([word.lower() for word in text if word not in
string.punctuation])
tokenize = re.split("W+", text)
text = [wn.lemmatize(word) for word in tokenize if word not in stopwords]
final = [word for word in text if word not in moreStopwords]
return final


filter_data = clean_text(pageData)
# get most common words & plot them on bar graph
most_common_words = [word for word, word_count in
Counter(filter_data).most_common(10)]
word_freq = [word_count for word, word_count in
Counter(filter_data).most_common(10)

mcw_lemma =
for token in most_common_words:
synsets = wordnet.synsets(token)
if synsets:
mcw_lemma.append(synsets[0].lemmas()[0].name())

fd_lemma =
for token in filter_data:
synsets = wordnet.synsets(token)
if synsets:
fd_lemma.append(synsets[0].lemmas()[0].name())

# Vectorizing most common words & filter data
mcw_vec = TfidfVectorizer(analyzer=clean_text)
fd_vec = TfidfVectorizer(analyzer=clean_text)
tfidf_mcw = mcw_vec.fit_transform(mcw_lemma)
tfidf_fd = fd_vec.fit_transform(fd_lemma)

# Create cluster
cluster = KMeans(n_clusters=len(mcw_lemma), max_iter=300,
precompute_distances='auto', n_jobs=-1)
X = cluster.fit_transform(tfidf_mcw)
pca = PCA(n_components=2).fit(X)
data2D = pca.transform(X)
plt.scatter(data2D[:, 0], data2D[:, 0],
c=numpy.random.random(len(mcw_lemma)))
plt.scatter(data2D[:, 0], data2D[:, 0],
c=numpy.random.random(len(fd_lemma)))
plt.show()


Suppose the most common words are:
['one', 'oasis', 'halliday', 'avatar', 'time', 'school', 'year', 'thing', 'old', 'stack']
They will be plotted in the graph and they should have their own clusters where the other words are plotted sharing the same lemma.










share|improve this question



























    0















    I am creating clusters of top 10 most common words, and my filter_data has the set of word token list. I am able to plot the clusters of those 10 words after vectorizing but after comparing the lemmas of the most common words with filter data I want to plot the word token list in the same graph. So that all the words get plotted into their own relevant clusters. How should I do that?



    I have tried vectorizing the data of most common words as well as the whole token list. Moreover, the top 10 most common words are being extracted out of the filter_data token list. In simple words I am trying to plot the semantic clusters using matplotlib.



    import string
    import re
    import nltk
    import PyPDF4
    import numpy
    from collections import Counter
    from sklearn.cluster import KMeans
    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.decomposition import PCA
    from nltk.corpus import wordnet
    import matplotlib.pyplot as plt

    # Declaring all the variables
    stopwords = nltk.corpus.stopwords.words('english')
    # additional stopwords to be removed manually.
    file = open('Corpus.txt', 'r')
    moreStopwords = file.read().splitlines()
    ps = nltk.PorterStemmer()
    wn = nltk.WordNetLemmatizer()
    data = PyPDF4.PdfFileReader(open('ReadyPlayerOne.pdf', 'rb'))

    pageData = ''
    for page in data.pages:
    pageData += page.extractText()


    def clean_text(text):
    text = "".join([word.lower() for word in text if word not in
    string.punctuation])
    tokenize = re.split("W+", text)
    text = [wn.lemmatize(word) for word in tokenize if word not in stopwords]
    final = [word for word in text if word not in moreStopwords]
    return final


    filter_data = clean_text(pageData)
    # get most common words & plot them on bar graph
    most_common_words = [word for word, word_count in
    Counter(filter_data).most_common(10)]
    word_freq = [word_count for word, word_count in
    Counter(filter_data).most_common(10)

    mcw_lemma =
    for token in most_common_words:
    synsets = wordnet.synsets(token)
    if synsets:
    mcw_lemma.append(synsets[0].lemmas()[0].name())

    fd_lemma =
    for token in filter_data:
    synsets = wordnet.synsets(token)
    if synsets:
    fd_lemma.append(synsets[0].lemmas()[0].name())

    # Vectorizing most common words & filter data
    mcw_vec = TfidfVectorizer(analyzer=clean_text)
    fd_vec = TfidfVectorizer(analyzer=clean_text)
    tfidf_mcw = mcw_vec.fit_transform(mcw_lemma)
    tfidf_fd = fd_vec.fit_transform(fd_lemma)

    # Create cluster
    cluster = KMeans(n_clusters=len(mcw_lemma), max_iter=300,
    precompute_distances='auto', n_jobs=-1)
    X = cluster.fit_transform(tfidf_mcw)
    pca = PCA(n_components=2).fit(X)
    data2D = pca.transform(X)
    plt.scatter(data2D[:, 0], data2D[:, 0],
    c=numpy.random.random(len(mcw_lemma)))
    plt.scatter(data2D[:, 0], data2D[:, 0],
    c=numpy.random.random(len(fd_lemma)))
    plt.show()


    Suppose the most common words are:
    ['one', 'oasis', 'halliday', 'avatar', 'time', 'school', 'year', 'thing', 'old', 'stack']
    They will be plotted in the graph and they should have their own clusters where the other words are plotted sharing the same lemma.










    share|improve this question

























      0












      0








      0








      I am creating clusters of top 10 most common words, and my filter_data has the set of word token list. I am able to plot the clusters of those 10 words after vectorizing but after comparing the lemmas of the most common words with filter data I want to plot the word token list in the same graph. So that all the words get plotted into their own relevant clusters. How should I do that?



      I have tried vectorizing the data of most common words as well as the whole token list. Moreover, the top 10 most common words are being extracted out of the filter_data token list. In simple words I am trying to plot the semantic clusters using matplotlib.



      import string
      import re
      import nltk
      import PyPDF4
      import numpy
      from collections import Counter
      from sklearn.cluster import KMeans
      from sklearn.feature_extraction.text import TfidfVectorizer
      from sklearn.decomposition import PCA
      from nltk.corpus import wordnet
      import matplotlib.pyplot as plt

      # Declaring all the variables
      stopwords = nltk.corpus.stopwords.words('english')
      # additional stopwords to be removed manually.
      file = open('Corpus.txt', 'r')
      moreStopwords = file.read().splitlines()
      ps = nltk.PorterStemmer()
      wn = nltk.WordNetLemmatizer()
      data = PyPDF4.PdfFileReader(open('ReadyPlayerOne.pdf', 'rb'))

      pageData = ''
      for page in data.pages:
      pageData += page.extractText()


      def clean_text(text):
      text = "".join([word.lower() for word in text if word not in
      string.punctuation])
      tokenize = re.split("W+", text)
      text = [wn.lemmatize(word) for word in tokenize if word not in stopwords]
      final = [word for word in text if word not in moreStopwords]
      return final


      filter_data = clean_text(pageData)
      # get most common words & plot them on bar graph
      most_common_words = [word for word, word_count in
      Counter(filter_data).most_common(10)]
      word_freq = [word_count for word, word_count in
      Counter(filter_data).most_common(10)

      mcw_lemma =
      for token in most_common_words:
      synsets = wordnet.synsets(token)
      if synsets:
      mcw_lemma.append(synsets[0].lemmas()[0].name())

      fd_lemma =
      for token in filter_data:
      synsets = wordnet.synsets(token)
      if synsets:
      fd_lemma.append(synsets[0].lemmas()[0].name())

      # Vectorizing most common words & filter data
      mcw_vec = TfidfVectorizer(analyzer=clean_text)
      fd_vec = TfidfVectorizer(analyzer=clean_text)
      tfidf_mcw = mcw_vec.fit_transform(mcw_lemma)
      tfidf_fd = fd_vec.fit_transform(fd_lemma)

      # Create cluster
      cluster = KMeans(n_clusters=len(mcw_lemma), max_iter=300,
      precompute_distances='auto', n_jobs=-1)
      X = cluster.fit_transform(tfidf_mcw)
      pca = PCA(n_components=2).fit(X)
      data2D = pca.transform(X)
      plt.scatter(data2D[:, 0], data2D[:, 0],
      c=numpy.random.random(len(mcw_lemma)))
      plt.scatter(data2D[:, 0], data2D[:, 0],
      c=numpy.random.random(len(fd_lemma)))
      plt.show()


      Suppose the most common words are:
      ['one', 'oasis', 'halliday', 'avatar', 'time', 'school', 'year', 'thing', 'old', 'stack']
      They will be plotted in the graph and they should have their own clusters where the other words are plotted sharing the same lemma.










      share|improve this question














      I am creating clusters of top 10 most common words, and my filter_data has the set of word token list. I am able to plot the clusters of those 10 words after vectorizing but after comparing the lemmas of the most common words with filter data I want to plot the word token list in the same graph. So that all the words get plotted into their own relevant clusters. How should I do that?



      I have tried vectorizing the data of most common words as well as the whole token list. Moreover, the top 10 most common words are being extracted out of the filter_data token list. In simple words I am trying to plot the semantic clusters using matplotlib.



      import string
      import re
      import nltk
      import PyPDF4
      import numpy
      from collections import Counter
      from sklearn.cluster import KMeans
      from sklearn.feature_extraction.text import TfidfVectorizer
      from sklearn.decomposition import PCA
      from nltk.corpus import wordnet
      import matplotlib.pyplot as plt

      # Declaring all the variables
      stopwords = nltk.corpus.stopwords.words('english')
      # additional stopwords to be removed manually.
      file = open('Corpus.txt', 'r')
      moreStopwords = file.read().splitlines()
      ps = nltk.PorterStemmer()
      wn = nltk.WordNetLemmatizer()
      data = PyPDF4.PdfFileReader(open('ReadyPlayerOne.pdf', 'rb'))

      pageData = ''
      for page in data.pages:
      pageData += page.extractText()


      def clean_text(text):
      text = "".join([word.lower() for word in text if word not in
      string.punctuation])
      tokenize = re.split("W+", text)
      text = [wn.lemmatize(word) for word in tokenize if word not in stopwords]
      final = [word for word in text if word not in moreStopwords]
      return final


      filter_data = clean_text(pageData)
      # get most common words & plot them on bar graph
      most_common_words = [word for word, word_count in
      Counter(filter_data).most_common(10)]
      word_freq = [word_count for word, word_count in
      Counter(filter_data).most_common(10)

      mcw_lemma =
      for token in most_common_words:
      synsets = wordnet.synsets(token)
      if synsets:
      mcw_lemma.append(synsets[0].lemmas()[0].name())

      fd_lemma =
      for token in filter_data:
      synsets = wordnet.synsets(token)
      if synsets:
      fd_lemma.append(synsets[0].lemmas()[0].name())

      # Vectorizing most common words & filter data
      mcw_vec = TfidfVectorizer(analyzer=clean_text)
      fd_vec = TfidfVectorizer(analyzer=clean_text)
      tfidf_mcw = mcw_vec.fit_transform(mcw_lemma)
      tfidf_fd = fd_vec.fit_transform(fd_lemma)

      # Create cluster
      cluster = KMeans(n_clusters=len(mcw_lemma), max_iter=300,
      precompute_distances='auto', n_jobs=-1)
      X = cluster.fit_transform(tfidf_mcw)
      pca = PCA(n_components=2).fit(X)
      data2D = pca.transform(X)
      plt.scatter(data2D[:, 0], data2D[:, 0],
      c=numpy.random.random(len(mcw_lemma)))
      plt.scatter(data2D[:, 0], data2D[:, 0],
      c=numpy.random.random(len(fd_lemma)))
      plt.show()


      Suppose the most common words are:
      ['one', 'oasis', 'halliday', 'avatar', 'time', 'school', 'year', 'thing', 'old', 'stack']
      They will be plotted in the graph and they should have their own clusters where the other words are plotted sharing the same lemma.







      python matplotlib wordnet






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 2 at 21:17









      TonyTony

      167




      167
























          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54013309%2fis-there-a-way-to-plot-the-two-different-sources-into-same-graph-using-matplotli%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54013309%2fis-there-a-way-to-plot-the-two-different-sources-into-same-graph-using-matplotli%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          How to fix TextFormField cause rebuild widget in Flutter

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith