Practice the major and minor scale fingering patterns, or "shapes," until you have mastered them. Each type of scale has a distinct pattern and can be moved to anywhere on the guitar. So for example, if you learn the major scale shape and want to play a G major scale, you would start out on the third fret of the low E string, because that is a G. Now take this shape and start out on the fifth fret of the low E string, and you will be playing the A major scale.
Play in key. Listen for the chord progression from the rhythm guitar. For instance, if the guitarist plays C major, F major, G major and then back to C major, then that would mean you should improvise in the key of C major. This is a one-four-five progression, because in the scale of C major, C is the first note, F is the fourth note and G is the fifth note. This progression is used frequently in all keys, so once you can recognize a one-four-five chord progression, you can determine the key.
Play little melodies while staying within the shape of the scale or chords for the key you are using. Experiment on the fretboard. Use various techniques such as bend, vibrato and slide and see which of them you prefer. The more you practice, the easier it will become.